Next Image not taking class properties

Before Next.js 12.2

Styling the next/image component’s margins this way doesn’t work in older Next.js versions. 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>

From Next.js 12.2

You can use the next/future/image component instead. This new component renders a single <img> element without any additional wrappers by default, and is no longer constrained by the wrapper’s styles override.

You can enable next/future/image in next.config.js.

module.exports = {
    experimental: {
        images: {
            allowFutureImage: true
        }
    }
}

From Next.js 13

The next/future/image component has been converted to next/image. Like next/future/image, this component renders a single <img> element and can be styled directly with className/styles.

Leave a Comment

tech