【问题标题】:What's the standard of width % for child positioned: absolute [duplicate]儿童定位的宽度百分比标准是什么:绝对 [重复]
【发布时间】:2021-12-14 04:38:22
【问题描述】:

据我所知,孩子的宽度百分比标准是父母的内容框(只有内容,没有填充或边距。)。因此,如果父项中有一个填充并且子项的宽度为 100%,则子项的宽度小于父项。但是如果我将孩子定位为绝对而父母定位为相对,无论父母的填充和边距如何,孩子的宽度都等于父母的宽度。像这样:

<div class="first">HI
<div class="second">
HELLO
</div>
</div>

css代码

 .first{
 background-color: yellow;
 width:100px;
 height:100px;
 padding:10%;
 position:relative;

}
.second{
background-color: blue;
position:absolute;
width: 100%;
height:100%;
opacity:40%;
 }

尽管父母的位置和相对所以孩子完全依赖于'.first'。这种情况下孩子的宽度标准是多少?

【问题讨论】:

    标签: html css position css-position absolute


    【解决方案1】:

    position:absolute 的 % 标准是最近定位的祖先块,如果没有定位祖先,它是相对于 body 元素的。在您的情况下,由于第一个是相对定位的,第二个将相对于第一个,如果您删除第一个的位置属性,第二个将相对于主体定位。

    您也可以查看这个 - https://www.w3schools.com/css/css_positioning.asp

    【讨论】:

      【解决方案2】:

      这个 sn-p 显示了将第二个 div 设置为具有相对位置然后是绝对位置的结果。您可以看到绝对定位的元素采用其父元素的宽度,包括内边距。

      .first {
        background-color: yellow;
        width: 100px;
        height: 100px;
        padding: 10%;
        position: relative;
      }
      
      .second {
        background-color: blue;
        width: 100%;
        height: 100%;
        opacity: 40%;
      }
      
      .relative {
        position: relative;
      }
      
      .absolute {
        position: absolute;
      }
      <h2>The blue square has relative position</h2>
      <div class="first">HI
        <div class="second relative">
          HELLO
        </div>
      </div>
      <h2>The blue square has absolute position</h2>
      <div class="first">HI
        <div class="second absolute">
          HELLO
        </div>
      </div>

      原因似乎是:

      当一个框有position: absolute 时,它的包含框是父级的填充框。

      查看接受的答案:Absolute positioning ignoring padding of parent 虽然我很难在实际的标准文档中找到确切的描述,如果有人能指出主要参考资料会很好。

      更新:感谢 Temani Afif 指出了这个有信息的SO answer。来自实际的specification

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 2020-03-07
      • 2016-11-10
      • 1970-01-01
      • 2013-01-23
      • 2021-08-10
      • 2021-11-09
      相关资源
      最近更新 更多