按比例调整背景图像大小

时间:2015-02-18 13:19:32

标签: javascript html css css3

我有一个容器div:

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

它有纵向和横向的背景图片:

#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');
    }
}

对于不同的屏幕尺寸,是否可以通过使用CSS或纯JS(无jQuery)按比例缩放图像?例如:对于横向图像,图像可能占据屏幕的整个高度,但两侧仍有一些边距(因为图像必须保持比例,但仍尽可能地填满屏幕)。在纵向中,它可能需要整个宽度,但在顶部和底部有一些边距。谢谢!

2 个答案:

答案 0 :(得分:0)

我强烈推荐Chris Coyier的Perfect Full Page Background trick

诀窍是将background-size属性设置为cover,将附件属性设置为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;
}

答案 1 :(得分:0)

你可以尝试

background-size: cover

background-size: contain

有关此属性的详细信息,请参阅here

相关问题