您的位置:首页 > 运维架构

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

2016-03-23 13:47 549 查看
当为父元素设定了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:-(子元素高度的一半)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css web前端