1. 程式人生 > >父元素高度為auto:子元素使用top:-50%沒有效果的問題

父元素高度為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:-(子元素高度的一半)