简体   繁体   English

按比例调整背景图像大小

[英]Resizing background image proportionally

I have a container div: 我有一个容器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? 对于不同的屏幕尺寸,有没有办法按比例缩放图像,使用CSS或纯JS(无jQuery)? 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 . 我强烈推荐Chris Coyier的完美全页背景技巧

The trick is setting the background-size property to cover, and the attachment property to fixed. 诀窍是将background-size属性设置为cover,将attachment属性设置为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 有关此酒店的详情,请参阅此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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