父元素高度为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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值