Home > Enterprise >  How to make NextJS Image component 100% height and width for its parent div?
How to make NextJS Image component 100% height and width for its parent div?

Time:07-06

As title, I am struggling to make Image behave like img, anyone know how to make Image achieve like img does as the example below?

  <div style={{ width: "100vw", height: "100vh", display: "flex" }}>
    {/* img */}
    <div style={{ width: "50%", height: "100%", background: "red" }}>
      <img
        src="https://t4.ftcdn.net/jpg/03/00/94/69/360_F_300946931_kSR84OqudEhsmBZH47HU6ud7aZIDMjEx.jpg"
        alt=""
        style={{ width: "100%", height: "100%", objectFit: "cover" }}
      />
    </div>
    {/* Image */}
    <div style={{ width: "50%", height: "100%", background: "blue" }}>
      <Image
        src="https://t4.ftcdn.net/jpg/03/00/94/69/360_F_300946931_kSR84OqudEhsmBZH47HU6ud7aZIDMjEx.jpg"
        alt=""
        width="1"
        height="1"
        layout="responsive"
        objectFit="cover"
      />
    </div>
  </div>

Output: example image

#UPDATE This is the answer.

      {/* Image */}
      <div
        style={{
          width: "50%",
          height: "100%",
          background: "blue",
          position: "relative",
        }}
      >
        <Image
          src="https://t4.ftcdn.net/jpg/03/00/94/69/360_F_300946931_kSR84OqudEhsmBZH47HU6ud7aZIDMjEx.jpg"
          alt=""
          layout="fill"
          objectFit="cover"
        />
      </div>

Output: enter image description here

CodePudding user response:

Ok, I see that you want the image to take the width and height of its parent element, you can just use layout="fill" instead of responsive, which causes the image to expand to fill its parent element.

Something like this:

<div style={{width: '100%', height: '100%', position: 'relative'}}>
  <Image
    alt='Mountains'
    src='/mountains.jpg'
    layout='fill'
    objectFit='contain'
  />
</div>

CodePudding user response:

Give it's parent a display of block

and take out the width and height properties preset

 <div style={{ width: "50%", height: "100%", background: "blue",display: "block" }}>
  <Image
    src="https://t4.ftcdn.net/jpg/03/00/94/69/360_F_300946931_kSR84OqudEhsmBZH47HU6ud7aZIDMjEx.jpg"
    alt=""
    layout="responsive"
    objectFit="cover"
  />
</div>

you can check the docs

  • Related