skip to Main Content

I am using Next JS 14 and Tailwind CSS

If I use fill this is code:

"use client";
import React from "react";
import { motion } from "framer-motion";
import Image from "next/image";

const Photo = () => {
  return (
    <div className="w-full h-full relative">
      <motion.div className="relative">
        <div className="w-[298px] h-[298px] xl:w-[498px] xl:h-[498px] mix-blend-lighten border-4 relative">
          <Image
            src="/assets/images/photo.png"
            priority
            quality={100}
            fill
            sizes="300px"
            alt="main"
            className="object-contain"
          />
        </div>
      </motion.div>
    </div>
  );
};

export default Photo;

But its image is not visible
If I use width and height its working
this is the code :

"use client";
import React from "react";
import { motion } from "framer-motion";
import Image from "next/image";

const Photo = () => {
  return (
    <div className="w-full h-full relative">
      <motion.div className="relative">
        <div className="w-[298px] h-[298px] xl:w-[498px] xl:h-[498px] mix-blend-lighten border-4 relative bg-gray-200">
          <Image
            src="/assets/images/photo.png"
            priority
            quality={100}
            width={298}
            height={298}
            alt="main"
            className="object-contain"
          />
        </div>
      </motion.div>
    </div>
  );
};

export default Photo;

What is the reason for this please help me to fix that, cant I use fill property here ?

2

Answers


  1. if you use fill property, you should have

    • parent element to be relative which you already set

    • next.js Image will take up all the "width" and "height" of the container parent element. Normally, if you do not set "width" and "height" of parent container, you wont see the image. that makes me think that those classes

      w-[298px] h-[298px]
      

    are conflicting. try to use arbitary h-96, w-96 to see if those work

    Login or Signup to reply.
  2. Use this code and set the height width of a parent div

    <Image src={"/images/landing/made-to-measure.jpg"} width="0" height="0" sizes="100vw" style={{ width: "100%", height: "auto" }} alt="" />
    

    What’s happening here-

    • Next Image component with source (replace the source string with your image path)
    • Width and Height is by default 0 to take parent element sizing
    • Sizes 100vw, this basically holds the quality of your image, you can change it to different vw to change the scaling quality
    • Style holds the basic CSS login for taking whole width and auto height.

    Placing this image component in your desired sized div component should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search