简体   繁体   中英

CSS: Responsive background image height

I'm using this CSS:

.wrap {
    max-width:1400px;
    min-width:768px;
    width:100%;
    background-repeat: no-repeat scroll;
    background-position: center top;
    position: relative;
    margin-top: 0;
    margin-right: auto;
    margin-bottom: 0;
    margin-left: auto;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.image {
    width: 100%;
    height: 600px;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

To center an image and scale it based on window size, stopping the scaling at 768px. I can't display the bottom part of the image when the window is at a larger size (it works fine when the window is minimized). When I change the height of the .image class to more than 600px, it breaks the image scaling...

Here's a demo of the problem: http://jrbaldwin.com/css_issue/

I think it's not scaling because the height is staying fixed. For example, set the .image height to 1000px. It has to enlarge the image to cover 1000px so it fills the entire 1000px height at all time, no matter what width the image is.

Possibly try:

background-size: 100%; background-repeat: no-repeat;

Building on @jtlowe's answer, couldn't you achieve the right effect by using background-size: contain instead?

Since you're already firmly in the CSS3 domain, you can optionally create a media query that uses cover in smaller size windows.

使用background-size:包含而不是cover。

Try this styles:

.image{
  width: 100%;
  height: 600px;
  max-height: 1000px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  max-height: 1000px;
}

The main idea is to use "contain" property
More information: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images

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