How can I ensure that the NextJS Image component fills its parent div completely in terms of both height and width?

Having trouble getting the Image component to behave like the img element? Can anyone provide a solution for making Image achieve the same result as shown in 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: https://i.sstatic.net/q5qj7.jpg

#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: https://i.sstatic.net/Oav80.jpg

Answer №1

Ah, I understand your request for the image to match the size of its containing element. You can achieve this by using the layout="fill" attribute instead of responsive. This will cause the image to expand and fill the area of its parent element.

Here is an example of how you can implement this:

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

Answer №2

Assign the parent element a display property of block

Remove the predefined width and height properties

 <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>

For more information, refer to the official documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue with height percentages being ineffective in CSS

My goal is to utilize the height property with percentages, however it seems to be ineffective. I desire to use percentages so that the layout appears well in various resolutions. <div id="bloque_1" style="height: 80%;background: red"> </div> ...

React sends back responses with numerous console.log statements

I have created a functional component, and when making an axios request, I received 2 undefined responses and 1 response with status code 200. I'm unsure why this is happening? Below is the code for my component : import { UidContext } from "../ ...

Uncovering the specific file housing a CSS definition

I'm currently navigating a complex webpage with numerous CSS files that were not authored by me. I am struggling to identify a CSS style that seems elusive, as it is not located in the most obvious places (such as the CSS files) and I have no idea whe ...

Conceal the content in order to determine the height of images displayed next to each

I am working on a layout where there are rows with images in the left column and text in the right column. The images have a ratio of 16:9. In case the text becomes too long, I would like to show only a portion of it with a gradient mask and provide a "Rea ...

What is the best way to retrieve the current value of 'count' when the component is mounted using socket.on("test")?

import ... let socket; const Game = () => { const ... const [userCount, setUserCount] = useState(0); const scrollToBottom = () => { endToMessages.current?.scrollIntoView({ behavior: "smooth" }); }; const { _id, username } ...

Display the header of the table after a page break in HTML using CSS

I have a unique question that is somewhat similar to others I've come across, like CSS: Repeat Table Header after Page Break (Print View). The difference in my question lies in the need for handling multiple headers. My query is about displaying the ...

Developing a Progress Bar in Next JS Version 13

I've been attempting to add a progress bar to my Next JS 13 app directory, but I have not had success with the traditional methods. Is there a solution for getting the progress bar to function properly? I have tried using the NextNProgress and NProgre ...

Adding CSS styles to an HTML page using JavaScript

Unfortunately, I do not have the ability to access the HTML directly as it is generated dynamically by a program. However, I do have access to the JS page that is linked to it. As an example, I am able to manipulate elements using JavaScript like so: ...

Show or conceal input fields depending on the selection of radio buttons

Hello everyone, I am new to JavaScript and currently learning. Can someone please assist me in fixing this code? The required inputs are: radio-button-1; radio-button-2; input-fields-set-1; input-fields-set-2; input-field-submit. My objective is: Upon ...

The typewriter effect is configured to appear as a separate layout,

<div className= "HomePage-typewriter"> I do{'\u00A0'} <Typewriter options={{ strings: [ '<span> this </span>', '<span> that </span>', '<span&g ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...

Creating a new method for injecting an API endpoint into both the backend and frontend of Next.js version 13, similar to the publicRuntimeConfig

Seeking a method to inject runtimeConfiguration accessible on both the client and server (graphql API endpoint for Apollo). I am working on a nextjs 13 app with Apollo Provider src/app/layout.tsx import type {Metadata} from "next"; import {Rubik ...

Bootstrap: Altering grid column layout for medium and small/extra-small screens

Hello everyone, I'm having a bit of trouble working with Bootstrap. My goal is to create a container with a row that contains three columns of equal width: <div class="row"> <div class="col-md-4" style="background:red;">logo</div& ...

IE9 causing trouble with CSS vertical alignment

I'm trying to center a button with text using Cuffon for the font, but I can't get it to align vertically and horizontally. The text-align property is working fine, but vertical align isn't. Here's the code for my div block: btndownlo ...

Utilize Bootstrap v4 in styling and aligning buttons for a polished

With Bootstrap v4 dropping the .btn-group-justified class, a solution can be found at https://github.com/twbs/bootstrap/issues/17631 Here's how to justify the buttons: <div class="btn-group btn-group-justified" role="group" aria-label="Justified ...

Fixing the error: "React-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a valid function"

Every time I change the option in the selector, I keep encountering this error: "react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function" :( import React from "react"; import Product from "./Product" ...

What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999. https://i.stack.imgur.com/0p6j3.jpg I have tried adding a mask to InputProps in my ...

Exploring React's conditional actions: comparing useEffect to if statements

I am a React beginner and I recently encountered something that I need clarification on. When dealing with conditional actions, is there a distinction between using useEffect versus simply having an if statement? function Items() { [setItemAdded, itemA ...

Discovering which chip has wrapped to the next line in Material UI Autocomplete can be found by closely inspect

Currently, I am working with a Material UI autocomplete feature that functions as follows: https://i.sstatic.net/4LrwI.png My goal is to determine when the fourth chip wraps to the next line within the autocomplete so that I can proceed with additional c ...

Having trouble displaying SVG elements in Material UI

Currently, I am faced with an issue while trying to display a .svg file in the header of a drawer using Material-UI and create-react-app. Instead of the expected .svg image, all I see is a broken image rendering. Any assistance on resolving this problem ...