What is the best way to set the width of a nextjs Image using CSS styles

Do you think it's more beneficial to use 'next/image' rather than the traditional img tag? If so, why?

I am trying to display an image by specifying width and height in styles using a class called 'img', like this...

<img className="img" src='url/img.png'/>

The 'img' class automatically sets the width and height in rem units. I'm unable to utilize the next/image tag because it requires specific pixel widths and does not support 'auto'. Is there any alternative solution for this issue?

One potential workaround is to wrap the img tag within a div element with the 'img' class and apply layout='fill', as shown below.

import Image from 'next/image';
<div className='img'>
<Image layout='fill' src="lll.jpg"/>
</div>

However, this approach feels unnecessary to me. What are your thoughts on this matter?

Answer №1

Is it better to use 'next/image' instead of the traditional img tag? If so, why?

Absolutely, opting for next/image over the standard HTML img tag is highly recommended. The reason being, next/image comes with an automatic optimization feature that ensures your images are loaded in the most efficient manner possible. It employs techniques like lazy loading, WebP format usage, and responsiveness, all while taking care of SEO aspects such as Layout Cumulative Layout Shift.

To delve deeper into this topic, you can refer to this informative answer:

In regards to the issue you mentioned, if you prefer not to directly specify width and height properties (which only support pixel units) for the next/image component, your best bet is to utilize layout="fill" along with a position:relative for its parent according to their documentation.

When set to fill, the image will expand both in width and height to match the dimensions of the parent element as long as the parent element has a relative positioning.
This combination usually goes hand in hand with the objectFit property.
Make sure the parent element includes position: relative in its stylesheet.

Therefore, your current approach seems appropriate given the requirement of having a parent for a next/image component with a layout='fill' attribute. Just ensure the parent has a position of relative.

Additionally, incorporating the sizes property is advisable to ensure the correct images are served based on the device. For further information, feel free to consult their 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

Having difficulty locating audio files within a Next.js project

I am facing challenges when trying to import my audio files into a redux slice. Currently, I am attempting to retrieve my audio files from the app > public > audio directory. I have made efforts to access my audio files through 2 different director ...

Discover the size of an image using JavaScript by accessing innerHTML

I'm currently working on a unique AJAX function that retrieves image URLs without using node append for insertion. Instead, I opted to utilize innerHTML, but this has posed challenges in accurately obtaining the file dimensions. My current approach i ...

How to Link to a new page using current page slugs in NextJS?

My current URL looks like this: http://localhost:3000/courses/italian/dynamic/lessons/wenC6hgETeMHSiFNabvk http://localhost:3000/courses/[language]/dynamic/lessons/[lessonID] I am searching for a simple way to access the .../exercises page. All I want to ...

Creating a Scrolling Element in CSS Without Displaying a Scrollbar

Find the visuals and code on JSbin here. Looking to create a left sidebar that is full height with a fixed position, yet have its content accessible without scrollbars and no need for overflow: scroll. I'm hoping to achieve this in CSS only, without ...

Error: Exceeded Maximum Re-Renders. React has set a limit on the number of renders to avoid infinite loops. Issue found in the Toggle Component of Next.js

I am struggling with setting a component to only display when the user wants to edit the content of an entry, and encountering an error mentioned in the title. To achieve this, I have utilized setState to manage a boolean using toggle and setToggle, then ...

What is the best way to adjust a component to display varying content based on the scenario?

I am looking for a way to reuse a component on my website that displays messages. The challenge is that in one section, the content consists of only a title and paragraph, while in another section, there are multiple titles and content pieces. I have imple ...

Scrapy and Python data gets corrupted by <br> tags causing issues

As I attempt to extract the text from Amazon reviews using scrapy, I encounter an issue. Reviews with multiple lines have their text separated by "< br >" tags within a span element. So, when I try to scrape the first review, I use this line of code: ...

Displaying the error message "No results found" in PHP AJAX live search with multiple values is not possible

I recently went through a tutorial on Most of it worked smoothly after setting it up on my local machine. However, I encountered an issue when searching for data not present in my database. I expected to receive an error message stating "No result found o ...

Aligning the content in the center of a div with inline display

Hi there, I have a quick question for the experts out there. I'm new to all of this so please bear with me :) I'm attempting to center an inline social sharing div on my website, but it's proving to be quite challenging. The div is nested w ...

Hey there, I'm looking to show a PDF on a webpage without having it available for download. Any

While working with Next.js and react-pdf, I encountered an issue where a user was able to access and download the PDF file by using Google Chrome's developer tools to find the link. Below is my pdfviewer.tsx page: "use client" import { useEf ...

Position a div at the bottom of another div using Bootstrap

I'm facing an issue with trying to position an inner div at the bottom of an outer div using bootstrap classes. I have attempted various methods in both bootstrap and regular CSS, such as vertical-align: bottom; and setting position to absolute, but n ...

The Boostrap card-deck appears to be see-through and malfunctioning

This problem has been puzzling me for quite some time now, and I just can't seem to find the solution! Kindly disregard the other language and code - the card is located under the jumbotron. (To access the link, remove spaces: https://code pen.io/ano ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

Customize the Emotion Styled Material UI Tab Indicator Overwrite

Looking for a way to customize the appearance of tab indicators using Emotion styled components. I'm struggling to target nested classes in my code. Here's what I have so far: const StyledTabs = styled(Tabs)( { classes: { indicator: ...

Encountering Double Axios API Calls on Page Load in Next.js 11

I've been working on migrating a React.js CRA to a Next.js SSR Application. I specifically switched to Next.js 11 because of some package dependencies that only support versions above 11. While my CRA application was running perfectly, after moving al ...

Designing a visually appealing widget in a jQuery UI theme by floating two elements neatly inside

My code looks like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Testing PasteHTML.co ...

Insert a line break into a tweet using JQuery

After installing this jquery plugin, I wanted to display my tweets on my website. However, the tweets are currently too close together and I need to add a line break between each one. Can anyone help me with how to achieve this? Below is the code I have b ...

Having difficulty setting up multiple buttons to share the same function in jQuery using HTML

After clicking a button, my code dynamically adds content to a div and inserts buttons with names like "teamReq_"+index+"_AddYear" into the document (where index is a number retrieved from a hidden input field). If these buttons are spammed, multiple divs ...

Emphasizing a full row within a table is a way to draw attention

I have a piece of HTML/CSS code that successfully underlines the text in a single table cell when hovering over it. However, I want to extend this effect to underline all text in a row of cells, rather than just one cell. It's not necessary for the en ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...