【问题标题】:Absolutely positioned child overflow parents borders绝对定位的子溢出父边界
【发布时间】:2015-05-28 23:35:25
【问题描述】:

我在相对(父)容器中有一个绝对定位(子)元素。我希望绝对定位的元素跨越其容器的整个宽度,包括填充和边框。

边框/填充可能有不同的大小,所以我不想硬编码偏移量。

这样的事情可能吗?

<div>
    <ul>
        <li>Test</li>
        <li>Test 2</li>
        <li>Test 3</li>
    </ul>
</div>


ul {
    position: absolute;
    left: 0;
    right: 0;
    background-color: red;
    border-bottom: 3px solid blue;
}

Here's a JSFiddle outlining the issue

【问题讨论】:

    标签: css position css-position


    【解决方案1】:

    如果不进行手动调整,就不可能让子元素覆盖其父元素的边框。即使在父级上使用box-sizing: border-boxposition: absolute 元素也只能从边框内部填充。 top: 0 将始终引用边框之前的最高像素。

    如果您想实现这一点,您需要手动调整。 calc() 可以提供帮助,但您可能需要先查看 browser support

    http://jsbin.com/qusita/1/edit?html,css,output

    .out {
      padding: 25px;
      position: relative;
      box-sizing: border-box;
      width: 200px;
      height: 200px;
      
      background-color: #555;
      
      border: 3px solid #aaa;
    }
    
    .in {
      top: 0;
      left: -3px;
      position: absolute;
      width: calc(100% + 6px);
      height: 100%;
      
      background-color: rgba(255, 0, 0, 0.5);
    }
    <div class="out">
      <div class="in"></div>
    </div>

    附带说明,ulol 元素通常有一定数量的默认边距/内边距,因此请注意这一点。


    这是使用更强大标记的替代方法。一般来说,有很多方法可以在 CSS 中实现相似的外观,有时您需要跳出框框(模型)思考一下。

    http://jsbin.com/taluko/1/edit?html,css,output

    .one {
      padding: 5px;
      position: relative;
      box-sizing: border-box;
      width: 200px;
      height: 200px;
      
      background-color: #777;
    }
    
    .two {
      width: 100%;
      height: 100%;
      
      background-color: #ccc;
    }
    
    .three {
      position: absolute;
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      
      top: 0;
      left: 0;
      
      background-color: rgba(255, 0, 0, 0.5);
      border-top: 5px solid #555;
      border-bottom: 5px solid #555;
    }
    <div class="one">
      <div class="two"></div>
      <div class="three"></div>
    </div>

    【讨论】:

      【解决方案2】:

      如果你有你父母的身高,你只需要加上top: 0bottom: 0。在这种情况下,孩子将被放置在没有填充的父容器中。

      但在您的情况下,它不起作用,因为绝对定位的子父级将为空,并且高度为 0 加上填充。

      作为变体,请参阅带有更新示例的小提琴: https://jsfiddle.net/5gtppy4x/1/

      我刚刚为孩子添加了topbottom,为父母添加了height

      【讨论】:

        猜你喜欢
        • 2021-03-04
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 1970-01-01
        • 2017-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多