Harsha M V
Harsha M V

Reputation: 54979

Nextjs Image component and setting width and height with CSS

I am using the Image component that ships with Next.js but its forcing me to set the width and height as values. I am using Tailwind CSS and using their utility classes to set the height and width.

enter image description here

<Image
      src={imageSrc}
      alt={name}
      className="object-cover object-center"
      layout="fill"
/>

The HTML Css Code that works is

enter image description here

<img
    className="w-auto h-6 lg:block"
    src="/img/logo-dark.png"
    alt="nftHODL.club Logo"
/>

Upvotes: 3

Views: 3284

Answers (2)

Lev Pleshkov
Lev Pleshkov

Reputation: 415

If the image is not loaded from the web source (hence its size is known at the time of creating a bundle) it's simpler to do this:

import YourImage from '../your/assets/image.png'
import styles from '../your/image.module.css'

<Image
  src={YourImage}
  alt='This is an image'
  className={styles.image}
/>

and specify the size and other properties in the CSS file.

Upvotes: 1

eahmann
eahmann

Reputation: 56

Adding a wrapper div with the size and relative classes and then setting layout="fill" on the Image component should do the trick.

Example:

<div className="h-64 w-96 relative"> // "relative" is required; adjust sizes to your liking
  <Image
    src={img.img}
    alt="Picture of the author"
    layout="fill" // required
    objectFit="cover" // change to suit your needs
    className="rounded-full" // just an example
  />
</div>

Source: https://techinplanet.com/how-to-use-tailwind-css-with-next-js-image/

Upvotes: 4

Related Questions