【问题标题】:Overflow child div background-color over parent div在父 div 上溢出子 div 背景颜色
【发布时间】:2023-03-31 05:19:01
【问题描述】:

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

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

CSS:

#parent {
    max-width: 760px;
}

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

【问题讨论】:

  • 澄清一下,您是想让.child 出现在#parent 之上?
  • @Peter 是的。我正在尝试为我的帖子标题做一个全宽背景。

标签: html css


【解决方案1】:

使用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>

【讨论】:

    【解决方案2】:

    如果您使用百分比,则当前代码设置无法实现您尝试做的事情,因为子级的 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;
    }
    

    【讨论】:

      【解决方案3】:

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

      #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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 2018-08-11
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 2012-01-13
        相关资源
        最近更新 更多