关于水平垂直居中 ,为什么没有垂直居中?
css3吧
全部回复
仅看楼主
level 1
嘿纸拜字 楼主
#parent {
width: 500px;
height: 200px;
background-color: #333;
position: relative;
}
#child {
height:30%;
width:50%;
background-color: #ccc;
position: absolute;
top: 50%;
left: 50%;
/*不知为何向上偏移量有点不对劲*/
margin: -15% 0px 0 -25%;
}
2016年07月21日 07点07分 1
level 1
嘿纸拜字 楼主
没有人吗?
2016年07月21日 11点07分 2
level 1
嘿纸拜字 楼主
有人知道为什么吗?
2016年07月21日 15点07分 3
level 1
嘿纸拜字 楼主
有人知道为什么吗?
2016年07月22日 10点07分 4
level 1
这个链接也许对你有帮助http://www.zhihu.com/question/20983035
2016年07月24日 02点07分 6
表示看不太懂
2016年07月24日 10点07分
level 2
<div class="parentBox">
<div class="childBox">我要居中</div>
</div>
.parentBox{
width: 500px;
height: 200px;
position: relative;
background: #ccc;
margin: 100px auto;
}
.childBox{
width: 60%;
height: 40%;
background: #f00;
position: absolute;
top:50%;
left:50%;
margin: -20% 0 0 -30%;
text-align: center;
}
子元素写百分比貌似不行啊,还是写具体值比较好
2016年07月29日 02点07分 9
但我还是不知道我的代码为什么没有居中的原因,不过还是感谢你
2016年08月01日 00点08分
我发现你的那个情况跟我的是一样的,只有水平居中,margin: -20% 0 0 -30%;变成margin: -10% 0 0 -30%;就可以了,不知道为什么
2016年08月01日 00点08分
level 3
改为
top: 35%;
left: 25%;
//margin: -15% 0px 0 -25%;
不用margin 了
2016年08月01日 10点08分 11
为什么这样改呢?
2016年08月01日 16点08分
level 1
大框架设置display:flex;要居中的div设置margin:auto;
2016年08月06日 01点08分 12
[汗]
2016年08月06日 14点08分
level 13
/*不知为何向上偏移量有点不对劲*/
margin: -15% 0px 0 -25%;
对于楼主这个疑问,6楼给的链接有正解。
margin中的百分比是相对于父容器中设置的宽度值,即你设置的-15%实际是相对于父容器中的宽度500px,
楼主可以尝试下,把高度改成和宽度一样,绝对能垂直居中。
2016年08月12日 04点08分 13
1