<div id="progressbarr">
当我使用 margin-top :50% 并期望它水平放置在中间时,仍然没有很好地包裹在它的祖先 div 中。
HTML 盒子
CSS
#col3wrap{
height: 50px;
background: #DDD;
}
.profilepic {
width: 50px;
height: 50px;
background: red;
float: left;
margin: 0 10px 0 0;
}
#progressbarr {
float: left;
width: 300px;
height: 20px;
background: #eee;
margin: 50% 0 0 0;
}
#progressbarr > div {
background-color: green;
width: 40%;
height: 20px;
}
最佳答案
您的边距值是使用父元素宽度计算的。为什么?好问题。我不知道,但这里有一些关于这个话题的讨论: Why are margin/padding percentages in CSS always calculated against width?
这是带有宽度设置的 #col3wrap
的演示:
http://jsfiddle.net/Xdwhk/1/
尝试调整宽度以查看 margin-top 值如何随之变化。
因此,除了使用 margin-top 之外,您将不得不找到一种不同的方法来使进度条垂直居中。
这是一种方法,使用 position: relative
和 calc
设置 top
值:
CSS
#col3wrap{
height: 50px;
background: #DDD;
position: relative;
}
.profilepic {
width: 50px;
height: 50px;
background: red;
float: left;
margin: 0 10px 0 0;
}
#progressbarr {
float: left;
width: 300px;
height: 20px;
background: #eee;
position: relative;
top: 30%;
top: -webkit-calc(50% - 10px);
top: calc(50% - 10px);
}
#progressbarr > div {
background-color: green;
width: 40%;
height: 20px;
}
备注calc并非所有浏览器都支持,因此我们必须退后一步。
关于html - 为什么 div 内的 div 不能很好地定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017751/