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

当为父元素设定了height:auto的时候,子元素设置position:relative top:50%没有效果的问题

代码如下:

<!DOCTPYE html>
<html>
<head>
    <meta content="text/html" charset="utf-8">
    <style type="text/css">
     html, body
      {
          width:100%;
          height:100%;
      }
      #one
      {
          position: absolute;
          top:50%;
          left:50%;
         <span style="color:#ff0000;"><strong> height:auto;</strong></span>
          width:auto;
      }
      .pa
      {
          position: relative;
          height:400px;
          width:200px;
          <strong><span style="color:#ff0000;">top:-50%;</span></strong>
          left:-50%;
          border:1px solid black;
          background-color:greenyellow ;

      }

    </style>
</head>

<body>
<div class="pr" id="one">

    <div class="pa pa1">#one的子元素pa1,相对#one绝对定位,#one是它的父元素,与.pa2为同级兄弟元素</div>

</div>

</body>
</html>
其实这段代码是想让 .pa 水平垂直居中的,可是并没有效果,top:-50%没有效果,如下图


正常情况下父元素设置height:auto应用获得子元素最大高度,在浏览器中也显示了父元素的模型高度是子元素高度400px,但是使用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的效果是一样的 。


当我们把height高度设定为固定值的时候:比如height:400px,代码如下,这时候子元素使用top:-50%就有效果了

<!DOCTPYE html>
<html>
<head>
    <meta content="text/html" charset="utf-8">
    <style type="text/css">
     html, body
      {
          width:100%;
          height:100%;
      }
      #one
      {
          position: absolute;
          top:50%;
          left:50%;
      <strong><span style="color:#cc0000;">  </span><span style="color:#ff0000;">  height:400px;</span></strong>
          width:auto;
      }
      .pa
      {
          position: relative;
          height:400px;
          width:200px;
      <strong>  <span style="color:#ff0000;">  top:-50%;</span></strong>
          left:-50%;
          border:1px solid black;
          background-color:greenyellow ;

      }

    </style>
</head>

<body>
<div class="pr" id="one">

    <div class="pa pa1">#one的子元素pa1,相对#one绝对定位,#one是它的父元素,与.pa2为同级兄弟元素</div>

</div>

</body>
</html>
结果如下图



所以,当父元素height设定为:auto的时候,子元素position:relative top:-50%,top:百分比值并不起作用,用px可以,比如:top:-(子元素高度的一半)


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值