Search code examples
reactjstypescriptnext.jsstyled-componentsnextjs-image

How put a Image component from next/image in position: absolue


Can I put an element Image from 'next/image' in { position: absolute; left: 50% }? It seems that it is not affected.

Example:

import React from 'react'
import Image from 'next/image'
import styled from 'styled-components'

const Container = styled.div`
  position: relative;
`

const Test = styled(Image)`
 position: absolute;
 left: 50%;
`

const Page: React.FC = () => {
  return (
    <Container>
      <Test src{someImg.webp} width={500} height={500} objectFit="none" />
    </Container>
  )
}

export default Page;

Solution

  • put your image in another parent div with position u like. in your case:

    import React from 'react'
    import Image from 'next/image'
    import styled from 'styled-components'
    
    const Container = styled.div`
      position: relative;
    `
     const ImageContainer = styled.div`
      position: absolute;
      left: 50%;
    `
    
    
    const Page: React.FC = () => {
      return (
        <Container>
         <ImageContainer>
            <Image src{someImg.webp} width={500} height={500} objectFit="none"/>
         </ImageContainer>
        </Container>
      )
    }
    
    export default Page;