将背景保持比率居中以拉伸以适应屏幕

时间:2013-12-06 11:50:12

标签: html css background wrapper

可能会出现一个初学者问题,但对此有困难。我正在使用'initialzr'中的模板来制作单页网页。页眉和页脚都没关系,但我希望有一个背景图像,我希望在这个div的屏幕上居中拉伸,这样屏幕将保持正确的比例。我看过几个使用绝对居中的网站和几个答案(Responsive Image full screen and centered - maintain aspect ratio, not exceed window)和(Scale background image so that it always keeps its aspect ratio and stays centered),并想知道这是否是采取它的方式?

我的代码几乎就是......

HTML:

 <div class="main-container">
        <div id="background"> 
        <img src="img/bg.png" style="no-repeat; background-size: cover;"/>
          <div class="main wrapper clearfix">
  <div id="header">
<p>test</p>
</div> 

CSS:

 #background img {
position: absolute;
min-height:100%;
width: 100%;
height: auto;
top: 0;
left: 0;
margin:0px auto;

}

当我运行此代码时,它覆盖整个屏幕,并且不显示我已经包含的页眉和页脚。非常感谢任何帮助或示例。对新手问题道歉,如果之前已经回答过。

干杯

2 个答案:

答案 0 :(得分:0)

它覆盖页眉和页脚的原因将归结为position:absolute;

您需要在img

z-index:-1;

或者在页眉和页脚上添加z-index。 (请记住应用z-index,它必须在元素上有定位。即position:relative

答案 1 :(得分:0)

请勿使用div来使用背景图像。将背景图像作为CSS属性放在body上。然后使用background-size: cover。这将使其尺寸尽可能大,同时覆盖整个区域并保持其纵横比。

body {
    background-image: url('images/image.png');
    background-size: cover;
    background-repeat: no-repeat;
}