Home > Mobile >  If image is not wide enough, how to make it stretch to the width of the window?
If image is not wide enough, how to make it stretch to the width of the window?

Time:01-16

The image is fine if it's not full screen, but with full screen, there's a white area on the right (probably because the image is not large enough). How do I make the image automatically stretch so that its width covers the full screen?

CSS (see .landingImage):

.body {
  margin: 0px, 50px;
}

.home {
  margin-left: 20px;
  margin-right: 20px;
  padding: 5px 5px;
}

.landingImage {
  z-index: 0;
  background-size: cover;
  top: 0;
  padding: 0;
  display: block;
  margin: 0 auto;
  width: 100vw;
}

index.js(built using nextjs):

<Head>
   ...
 </Head>
 <div id="wrapper">
    <Image className={indexStyles.landingImage} src={orcas} />
  </div>
      <div className={indexStyles.home}>
        <Head>
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1"
          ></meta>

          <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
          ></link>
        </Head>
        <body>
            ...
        </body>
      </div>

tried width: 100% also didn't work

CodePudding user response:

from the doc

When using layout='fill', the parent element must have position: relative

This is necessary for the proper rendering of the image element in that layout mode.

What can you do is :

CSS :

add relative to the landingImage class and remove margin auto

.landingImage {
  z-index: 0;
  background-size: cover;
  top: 0;
  padding: 0;
  display: block;
  width: 100vw;
  position: relative;
}

Wrap Image on the div

<div className='landingImage '>
    <Image 
        layout='fill' // required
        objectFit='cover' // change to suit your needs
        src='orcas' //
    />
</div>
  •  Tags:  
  • Related