保持div的宽度与包装器相同,但使背景全宽

时间:2013-05-07 01:27:59

标签: css html background

图像显示了我想要完成的任务。所有3个div都包含在800px的包装中。但是第二个div的背景延伸了整个身体的宽度。

enter image description here

2 个答案:

答案 0 :(得分:1)

你可以做到这一点的一种方法是让三个独立的div在内部对齐,全宽背景并相互堆叠。

<div class="top">
    <div class="wrap">
        <p>Some content</p>
    </div>
</div>

<div class="mid">
    <div class="wrap">
        <p>Some content</p>
    </div>
</div>

<div class="bottom">
    <div class="wrap">
        <p>Some content</p>
    </div>
</div>

CSS是:

body {
  text-align: center;
}

.top, .bottom {
  background: #aaa;
  width: 100%;
}

.mid {
  background: #616161;
  width: 100%;
}

.wrap {
  width: 800px;
  margin: 0 auto;
  padding: 5px;
}

答案 1 :(得分:1)

我的解决方案几乎与patkay的解决方案相同。

我的HTML:

<div class="outer-wrapper">
    <div class="inner-wrapper">
        <div class="content">Content 1...</div>
    </div>
    <div class="inner-wrapper noted">
        <div class="content">Content 2...</div>
    </div>
    <div class="inner-wrapper">
        <div class="content">Content 3...</div>
    </div>
</div>

我的CSS:

.outer-wrapper {
    width: 100%;
    outline: 1px dotted blue;
}
.inner-wrapper {
    width: inherit;
}
.inner-wrapper.noted {
    background-color: gray;
}
.content {
    width: 600px;
    margin: 10px auto;
    outline: 1px dotted red;
}

小提琴参考:http://jsfiddle.net/audetwebdesign/Nbu7G/

基本上,我使用.outer-wrapper来设置控制整体宽度,然后将宽度继承到.inner-wrapper,用于通过额外的类调用.noted设置背景颜色

最里面的容器.content具有固定的宽度(例如,600px)。

额外的标记可以使用HTML5标签进行语义清理,但是这种模式可以为你提供很多钩子来使用背景图像等等。

相关问题