在父div上溢出子div背景颜色

时间:2018-10-26 20:24:43

标签: html css css3

是否有办法使child-div的背景颜色溢出其parent-div容器?我正在尝试添加全屏宽度的background-color,但parent-div具有固定的宽度。这是我的HTML结构:

<div id="parent">
    <div class="child">PAGE TITLE</div>
</div>

CSS:

#parent {
    max-width: 760px;
}

.child {
    width: 100%;
    background-color: red;
}

3 个答案:

答案 0 :(得分:0)

在当前的代码设置下,您尝试做的事情是不可能的,因为如果使用百分比,则将孩子的z-index与其父对象设置为与父对象相同的堆叠索引。

您需要执行类似的操作才能获得所需的结果。

HTML

<div id="parent">
    <div class="child">PAGE TITLE</div>
</div>

<div id="page"></div>

CSS

#parent {
    max-width: 760px;
    background: green;
}

.child {
    width: 100%;
    background-color: red;
}

#page {
    width: 760px;
    height: 760px;
    background: green;
    position: relative;
    z-index: 1;
}

答案 1 :(得分:0)

不知道这是不是您想要的。

#parent {
    max-width: 760px;
    margin: 10px auto;
}

.child:before {
    width: 100%;
    height: 24px;
    content: ' ';   
    position: absolute;
    left: 0;
    z-index: -1;
    background-color: green;
}

注意:#parent的背景颜色必须透明才能使这些CSS工作。

检查我的fiddle

答案 2 :(得分:0)

使用box-shadow模拟背景溢出,因为它是纯色:

#parent {
  max-width: 760px;
  height: 100px;
  padding: 10px 0;
  margin:auto;
  background:blue;
}

.child {
  width: 100%;
  height: 100%;
  background-color: red;
  box-shadow:
    760px 0 0 red,
    1520px 0 0 red,
   -760px 0 0 red,
   -1520px 0 0 red;
}
<div id="parent">
  <div class="child">PAGE TITLE</div>
</div>