How to Set NextJS Images with auto Width and Height ?

Images play a crucial role in web development, enhancing visual appeal and conveying information effectively. With Next.js, a popular React framework, optimizing images for various screen sizes while maintaining quality and performance is essential. In this article, we’ll explore two approaches to set Next.js images with auto width and height.

Steps to Create NextJS Application

Step 1: Create a nextJS application by using this command

npx create-next-app my-app

Step 2: Navigate to the project directory

cd my-app

Project Structure

The updated dependencies in package.json file will look like.

 "dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.3"
}

Using the layout Prop

  • The layout prop dictates how an image resizes within its container
  • layout = “fill” makes the image fill its entire container while maintaining aspect ratio
  • This approach works well with responsive layouts as the image will resize automatically based on the container’s size.
  • You only need to set layout=”fill” on the next/image component which keep your code clean and concise.

Example: Implementation to change the image width and height according to screen size using layout method.

JavaScript
// pages/index.js

import Image from 'next/image';

const MyComponent = () => (
    <div className="image-grid">
        <h1 className='title'>w3wiki</h1>
        <div className="grid-container">
            <div className="grid-item">
                <Image src=
"https://media.w3wiki.net/wp-content/uploads/20240507124344/q2.png" 
                    alt="Image 1"
                    objectFit="cover" layout="fill" />
            </div>
            <div className="grid-item">
                <Image src=
"https://media.w3wiki.net/wp-content/uploads/20240507124344/q2.png" 
                    alt="Image 2"
                    objectFit="cover" layout="fill" />
            </div>
            <div className="grid-item">
                <Image src=
"https://media.w3wiki.net/wp-content/uploads/20240507124344/q2.png" 
                    alt="Image 2"
                    objectFit="cover" layout="fill" />
            </div>
            <div className="grid-item">
                <Image src=
"https://media.w3wiki.net/wp-content/uploads/20240507124344/q2.png" 
                    alt="Image 2"
                    objectFit="cover" layout="fill" />
            </div>
        </div>
        <style jsx>{`
      .title {
        color: green;
      }
      .image-grid {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .grid-container {
        display: grid;
        /* Adjust the minmax width as needed */
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); 
        gap: 16px; 
        justify-items: center;
        width: 100%;
        max-width: 1200px;
        margin-top: 20px;
      }
      .grid-item {
        position: relative;
        width: 100%; /* Ensure grid items take full width */
        height: 0; 
        padding-bottom: 75%; 
      }
    `}</style>
    </div>
);

export default MyComponent;

Output:

Customizing with CSS for Fluid Layouts

  • CSS offers precise manipulation of image scaling and positioning within containers through properties like width, height, and object-fit, enabling developers to achieve pixel-perfect adjustments.
  • This method shines in fluid layouts where images must seamlessly adjust to varying screen sizes while preserving their aspect ratio, ensuring consistent visual presentation across devices.
  • CSS unlocks a range of styling possibilities beyond basic scaling, including the addition of borders, filters, and other effects, allowing for enhanced visual aesthetics and creative design choices.

Example: Implementation to change the image width and height according to screen size using custom CSS .

JavaScript
// pages/index.js
import Image from 'next/image';

const MyComponent = () => ( 
    <div>
      <Image
        src="/image/gfg.png"
        alt="Example Image"
        width={500}
        height={500}
        style={{ width: '100%', height: 'auto' }}
      />
    </div>
);

export default MyComponent;

Output: