父元素高度为auto,子元素使用top:-50%没有效果的问题

无意间在实现元素垂直居中的一种方式测试到,当一个元素高度没有指定的情况下,其 postion:relative;top:-50%;无效

后来查阅w3c看到这样一句话:

<percentage> 百分比

The offset is a percentage of the containing block's width (for 'left' or 'right') or height (for 'top' and 'bottom'). For 'top' and 'bottom', if the height of the containing block is not specified explicitly (i.e., it depends on content height), the percentage value is interpreted like 'auto'.
如果父元素的高度没有明确指定,top 的值跟设定为auto的效果是一样的 。

1  <div style="position: absolute; left: 50%;top:50%;border:1px solid green">
2         <div style="position: relative; left: -50%; top:-50%;border: dotted red 1px;">
3             I am some centered shrink-to-fit content! <br />
4             tum te tum
5         </div>
6     </div>

但是当指定特定值的时候就会有效果, height:36px;

 <div style="position: absolute; left: 50%;top:50%;height:36px;border:1px solid green">
        <div style="position: relative; left: -50%; top:-50%;border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>

  

  

原文地址:https://www.cnblogs.com/czhyuwj/p/5677924.html