Tips for creating the Next.js Image component to simulate the behavior of a standard <img> tag

I have been grappling with this issue for hours and I'm at a loss for what to do next.

Here is how my Image component is wrapped:

<div className={styles.featureImgContainer}>
  <Image
    src={
      post.feature_image
    }
    alt={post.title}
    fill
    className={styles.featureImg}
  />
</div>

and here is the associated styling:

.featureImgContainer {
  position: relative;
  width: 100%;
  height: 500px;
}
    
.featureImg {
  object-fit: contain;
}

The issue arises when the image does not take up the full width of the container due to the constrained height, maintaining its aspect ratio. This results in unnecessary margins on top and bottom.

As I resize the viewport, the image eventually spans the full width but creates additional unwanted space above and below:

https://i.sstatic.net/NBfHo.png

Removing or setting the height of the image container to auto causes the image to disappear. Ideally, I would like the image and container to always be at 100% width with automatic height adjustment.

Typically, using a regular < img > tag within an unspecified height container with 100% width adjusts the image height automatically while maintaining aspect ratio without white space.

How can I achieve similar behavior with the Next.js Image component? I want to simply insert my image with or without a container, specifying only the desired width (100% in this case).

Answer №1

It may be beneficial to consider removing the fill prop from the <Image> component, as recommended in the official documentation:

[…] causes the image to fill the parent element […]

Instead, it is suggested to set a specific width and height prop (potentially based on the expected dimensions at a certain container width) and then applying width: 100%; height: auto to proportionally scale the image while filling the parent width:

.featureImg {
  width: 100%;
  height: auto;
}

You can remove the height declaration from the .featureImgContainer to allow the element to inherit its height from the inner <img> element with height: auto.

For an example of this technique in action, refer to the Next.js demo and view its source code.

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

Using AJAX in a Django application within a RESTful ecosystem

I am new to the world of restful programming and have a Django website. My goal is to dynamically load a part of the website. Currently, my workflow is as follows: When I call a URL (such as localhost:8080/index), it routes to the Django view, which retr ...

The problem of interpreting JSON using the JavaScript eval() function

Here is the JSON string provided : { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name ...

Seeking assistance with printing an HTML template using a printer in Angular 2. Can anyone provide guidance on how

I have a scenario where I need to print an HTML template from within my Angular 2 component. Specifically, I want to be able to click on a print button on the same page and trigger the print function, which would display a print preview and allow the use ...

Response received from the server

I am looking to display server response error messages within a form after submission. By using the following code in my JavaScript, I am able to retrieve the error message: .error(function (data, status, header, config) { $scope.postDataSuccessfully ...

Prevent Image Clicks & Protect Text from Copying with HTML and CSS

So, I have an image that is supposed to direct you to a specific URL when clicked. However, the image is currently unclickable and there's a text box below it that cannot be copied. This issue arose after I used CSS to position the image and text box. ...

The use of url.resolve() function with greater than two arguments

Currently, I'm utilizing the url.resolve() function to combine components of a URL from a configuration file in this manner: var uri = url.resolve(config.baseUrl, this.orgId, this.appId, type) However, it appears that using more than two arguments d ...

The Spotify Whitelisted URI may show an error message: { "error": "invalid_grant", "error_description": "Redirect URI is invalid" }

Although there are similar questions out there, I'm facing a different issue. I am trying to obtain an access token from Spotify API, but all I keep getting is the dreaded "invalid redirect uri" error. Below is my API call: const request = require(& ...

Events triggered when a Jquery checkbox is toggled between checked and unchecked

I have written some HTML code that utilizes jQuery to manage checkboxes. <tr> <td> <div class="checkbox"> <label><input type="checkbox" id="checkbox2"></label> </div> </td> & ...

Before computing the width, Next.js Swiper slide occupies the entire width

Check out the code snippet below: 'use client'; import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css'; import 'swiper/css/pagination'; export default function Component() { const cards = [{ id: 0 ...

Having trouble retrieving an element's attribute using jQuery

I am facing an issue with the following HTML code: <img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt=""> I am attempting to achieve the following functionality: $('body').on(&apos ...

Experiencing trouble with calculating the total value of an array of objects due to NaN errors

I've been working on developing this web application in VUE.js, but I'm facing an issue with a specific function where I am attempting to sum the values of each object within an array. This is resulting in a NaN (Not a Number) error. Let's t ...

Distinguishing Font Sizes in Safari Compared to UIWebView

When the page is loaded in Safari, everything looks perfect. However, when viewed in a UIWebView, all the fonts appear enlarged. I've done my research and tried various solutions like: - Setting WebView.scalesPageToFit = true - Applying default con ...

Expanding Highcharts Tooltip Size Automatically Based on Content Updates

I am dealing with a Highcharts graph that has tooltips showing a loading spinner upon hover. These tooltips fetch data from the server via AJAX, but when the content is updated, it overflows due to the tooltip not resizing. Below is the SCSS code snippet I ...

Challenge encountered while using the like operator with Integer data type in Mongoose

I am encountering an issue with constructing a where query in Mongoose for an integer data type. The key 'facevalue' is of integer data type. When I execute a find query, it appears something like this: Below is the code snippet: var orCond ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

What is the best way to enable an image to be moved on top of another image?

Is there a way to allow users to drag around an image that is positioned on top of another image in an HTML file? I want the superimposed image to stay within the boundaries of the underlying image. Any suggestions on how this can be achieved? <html& ...

retrieve the information stored in the rows of the table

Here is the arrangement, with numerous div class="extra" elements in my project. <div class="extra"> <table width="90%"> <colgroup> <col width="40%"/> <col width="30%"/> <col width="30% ...

Storing a table structure in a variable using JavaScript

Kindly review this arrangement: 1 | 2 | 3 | .... ---------------------------------------------------------- 2016 100 2000 500 2015 540 450 1200 2014 120 230 660 I am seeking a method ...

Is it possible for one div to prompt an ajax response in another div?

In my attempt to create a main page with 3 div sections, I am using ajax to sequentially load content into each area. The idea is to have div1 already loading the page fetched from ajax as soon as the main page loads. This includes heavy mysql operations o ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...