简体   繁体   中英

CSS make Image centered on mobile view while keeping height the same?

Here's my codesandbox https://codesandbox.io/s/white-pine-8tfws?file=/styles.css

Right now if you shrink the screen, the image just disappears into the right side. I'd like to have the image centered on smaller screen sizes instead of showing just the left side of the image. I tried to just have it span the full width, but when I shrink it the quality becomes terrible and just looks blurry.

This website is an example effect I'm trying to replicate https://www.jamesedition.com/real_estate except maybe keep the height the same ratio

I hard coded the tags in my HTML, so I don't know how I would position it since I can't use the background: URL() property because it's a slider and I have to map through a data file.

Here's the css

           * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      .main {
        position: relative;
        max-height: 1100px;
        height: 100vh;
        width: 100vw;
        margin-top: -60px;
        z-index: 1;
        overflow-x: hidden;
      }

      .section {
        position: absolute;
        top: 0;
        left: 0;
        height: 100vh;
        z-index: -1;
      }

      h1 {
        position: absolute;
        top: 50%;
        left: 10%;
        font-size: 1.5rem;
        color: #fff;
        text-transform: uppercase;
      }

      img {
        height: 100vh;
        width: auto;
        min-width: 100vw;
      }

just replace your img css, hope this is what you are looking for,

img {
  height: 100vh;
  width: 100%;
  object-fit: contain;
  object-position: center top;
}

      height: 100vh;
  width: auto;
  min-width: 100vw;
  background: url('src="https://images.unsplash.com/photo-1564013799919-ab600027ffc6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"') no-repeat center center;
}

add this style in your image:

  height: auto;
  width: 100vw;
}

Here add a min-height if required.

it'll keep your image full width and keep height auto so that image quality will not be compromised. It's quite hard to keep one image for all devices and don't lose the quality, since viewport changes and aspect ratio also needs to be changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM