简体   繁体   中英

Resizing background image proportionally

I have a container div:

<div id="fullpage" class="fullpage_bg">
    ...rest of the elements
</div

It has a background image for portrait and landscape:

#fullpage {background-color: rgba(0,0,0,0.2); background-position: center center;}
@media screen and (orientation:portrait) {
    .fullpage_bg{
        background-image: url('images/bg_portrait.jpg');
    }
}
@media screen and (orientation:landscape) {
    .fullpage_bg{
        background-image: url('images/bg_landscape.jpg');
    }
}

Is there a way to scale the image proportionally, either by using CSS or pure JS (no jQuery), for different screen sizes? For example: for landscape the image might take the entire height of the screen, but still have some margins on the sides (because the image must maintain proportions, but still fill the screen as much as possible). In portrait it might take the entire width, but have some margins on top and bottom. Thanks!

I highly recommend Chris Coyier's Perfect Full Page Background trick .

The trick is setting the background-size property to cover, and the attachment property to fixed.

 html { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } 

You can try

background-size: cover

or

background-size: contain

See here for more details on this property

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