2

I use the Next.js <Image /> component to load the logo in my header. I want to position the component within the header. In short, I need to specify its margin.

    <div className={styles.header}>
      <Image src={logo} alt="logo" />
      <nav>navbar</nav>
      <ul>
        <li>opt1</li>
        <li>opt2</li>
        <li>opt3</li>
      </ul>
    </div>

I know that I can simply place the <Image /> inside a positioned block, but is there a way to do it directly?

gorniczy
  • 67
  • 1
  • 7

4 Answers4

5

No there is not. You can modify many properties by passing className prop to next/image. But since margin is relative to the wrapper, modifying it won't help you.

What you are trying to do requires setting styles on the wrapper inserted over img tag by next/image, which currently is not possible (directly). See this discussion for better insight.

However, as a workaround (for your particular case) you can add the styles on your header that select the wrapper div. Refer: CSS Combinators

.header > div {
   margin-left: 2em;
}

Update: In newer versions you can use the experimental image component that renders img without any wrapper.

brc-dd
  • 10,788
  • 3
  • 47
  • 67
2

I think using styled-components is a pretty way.

import Image from 'next/image';
import styled from 'styled-components';


const StyledImage = styled(Image)`
  /* your custom style */
  margin: 10px;
`;

and using it: <StyledImage src={image_path} />
Saeed Hemmati
  • 453
  • 2
  • 11
0

As nextjs documentation on Image component says you can use className for styling the same way as you do with your usual elements.

Kiril
  • 131
  • 5
-1

You can apply class name to the <Image/> component. E.g.

<Image
  className="dummy-name" 
  src={src} 
  width={2400} 
  height={1598} 
  layout="responsive"/>

Documentation has listed some useful properties.

Sana Mumtaz
  • 803
  • 7
  • 16