将子 div 扩展到容器 div 之外的两边,边距:0 auto

Ema*_*gux 4 html css

假设我有一个包含子 div 的 div。容器 div 设置为margin: 0auto,因此当宽度增加时,div 会在两侧扩展。如果此容器内的 div 也设置为margin: 0自动,是否有办法让此 div 扩展到其容器 div 之外并同样向右和向左延伸?

下面的例子表明,当.background 的宽度增加到超过容器的宽度时,它的大小只从右侧增加,而不是从两侧增加。

css 和 html:

.container {
  width: 600px;
  background-color: lightgreen;
  margin: 0 auto;
}
.background {
  width: 300px;
  margin: 0 auto;
  background-color: blue;
}
.content {
  width: 200px;
  background-color: lightblue;
  margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)
<div class = "container">
  <div class = "background">
    <div class = "content">
      content
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/DpYGm/2/

这一切都是为了让横幅图形背景图像跨越页面的主体宽度,但仍然使页面内部的内容保持不变。

ral*_*h.m 5

假设您希望backgrounddiv 在每一侧突出 50 像素。你可以在你的 CSS 中做到这一点:

.background {
    margin: 0 -50px 0 -50px;
    background-color: #00F;
}
Run Code Online (Sandbox Code Playgroud)

一个完整的例子:

.background {
    margin: 0 -50px 0 -50px;
    background-color: #00F;
}
Run Code Online (Sandbox Code Playgroud)