如何让背景图片超出max-width div

时间:2014-10-22 08:21:00

标签: css html5

我有一个响应式网站,最大宽度设置为1000px,但我需要适合与其中一个div重叠的背景图片,并将整页宽度底部边框放置到其他div。

我的代码是这样的:

.container { 
width: 100%; 
max-width: 1000px;
}


.logotest {
background-color: #03b9e5;
height: 50px;
}

.navtest {
background-color: #e4ed00;
height: 25px;
}

.socialtest {
background-color: #ab801a;
height: 25px;
}

.main {
height: 750px;
background: url(background.jpg) no-repeat top center;
margin: auto;
}

.line {
border-bottom: 1px solid black;
}

.container:after {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
<body>
<div class="container" id="first">
<div class="logotest">
</div>
<div class="socialtest">
</div>
<div class="navtest">	
</div>   
</div>
<div class="line"></div>

<div class="main line" id="second">

</div><div class="container">
<div id="third">
</div>
</div>
</body>

我得到第一个div正确的宽度和底部边框跨越整个页面宽度,第二个div已经显示了背景图片,但最大宽度1000px不再适用。正确显示底部边框(分割第二个和第三个div),第三个div再次应用了正确的最大宽度。

我做错了什么/没做什么来获得第二个div的最大宽度?

1 个答案:

答案 0 :(得分:1)

您的解决方案

如果background-size属性的浏览器支持足够好,您可以使用background-size: cover;。查看herehere以查看浏览器支持。

以下是显示其工作原理的代码段。如果您希望将背景图像始终居中,请务必将背景图像定位到center center

.container {
  width: 100%;
  max-width: 300px;
  margin: 0 auto;
}
.line {
  border-bottom: 1px solid black;
}
.logotest {
  background-color: #03b9e5;
  height: 50px;
}
.navtest {
  background-color: #e4ed00;
  height: 25px;
}
.socialtest {
  background-color: #ab801a;
  height: 25px;
}
.main {
  height: 250px;
  background: url(http://lorempixel.com/250/250) no-repeat center center;
  background-size: cover; /* This does the magic */
}
.container:after {
  clear: both;
  content: ".";
  display: block;
  height: 0;
  visibility: hidden;
}
<body>
  <div class="container" id="first">
    <div class="logotest">
    </div>
    <div class="socialtest">
    </div>
    <div class="navtest">
    </div>
  </div>
  <div class="line"></div>


  <div class="main" id="second">
    <div class="container">Put your content in here.</div>
  </div>
  <div class="line"></div>
  <div class="container">
    <div id="third">
    </div>
  </div>
  <div class="line"></div>
</body>


最后(但不是最少)

您可能想查看一篇关于网页设计中响应式图片状态的精彩文章,如果您要进行自适应网页设计,这将有助于您:Responsive images done right.