Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next Image not taking class properties

I am using Next.js and next/image to display images, but the CSS is not working inside it. The image is in SVG format and I have placed it in the public folder. I am using Tailwind CSS along with this.

<Image
  className="mt-3"
  data-testid="close-icon"
  src="/CloseIcon.svg"
  alt="Close Nav Bar"
  height="24"
  width="24"
/>

I am not sure why it is not working and it is not being reflected in the browser. Any help will be greatly appreciated!

like image 223
vikky Avatar asked Jan 01 '21 05:01

vikky


People also ask

Why does next image generate inline styling that resets my CSS?

The reason that this is an issue is because I am building a automated html to nextjs converter. If it was just for a single project this would not be an issue :/ Adding a div wrapper to override the image style will not work since your dealing with an inline style. Try to look at CSS specificity.

Can I use IMG in next js?

How to Render Images in Next. js. There are two ways you can display images in Next. js, you either use the conventional <img> tag or a specialized <Image/> component that is unique to Next.


2 Answers

Styling the next/image component's margins this way currently doesn't work. See relevant GitHub discussion for more details.

Internally to the next/image component, the img element and the elements that wrap it have inline styles that override certain values passed through className.

As a workaround, you can add a wrapper element and apply the margin styling to it instead.

<div className="mt-3">
    <Image
        data-testid="close-icon"
        src="/CloseIcon.svg"
        alt="Close Nav Bar"
        height="24"
        width="24"
    />
</div>
like image 114
juliomalves Avatar answered Oct 20 '22 23:10

juliomalves


Juliomalves's answer is right, but I would prefer:

<div className="mt-3" height="24" width="24">
    <Image
        data-testid="close-icon"
        src="/CloseIcon.svg"
        alt="Close Nav Bar"
        layout="fill"
    />
</div>

You also can use a little cheat:

import {motion} from "framer-motion";

    <motion.img 
      className="mt-3"
      data-testid="close-icon"
      src="/CloseIcon.svg"
      alt="Close Nav Bar"
      height="24"
      width="24">
like image 25
Andrew Kruglik Avatar answered Oct 21 '22 01:10

Andrew Kruglik