我想要一个通过百分比的操作边缘的子div.y位置应为父div的50%.但它在某种程度上更多.为什么不是50%?
HTML
<div class="content">
<header></header>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.content {
width: 300px;
height: 200px;
background: blue;
position: relative;
clear: both;
}
.content header {
width: 100px;
height: 100px;
margin-top: 50%;
background: red;
position: relative;
float: left;
}
Run Code Online (Sandbox Code Playgroud)
Ter*_*rry 16
这是因为当以百分比形式显示顶部/底部边距和填充时,这些值将被视为父元素的小数宽度,而不是高度.根据W3C的定义:
[margin]百分比是根据生成的框的包含块的宽度计算的.请注意,对于"margin-top"和"margin-bottom"也是如此.如果包含块的宽度取决于此元素,则在CSS 2.1中未定义结果布局.
这个问题之前已在StackOverflow中得到解决 - 请参见此处.
建议:如果要将元素垂直放置在中心,可以使用以下技巧:
这是你的小提琴中修改过的CSS有效:
.content header {
width: 100px;
height: 100px;
top: 50%;
background: red;
position: absolute;
-webkit-transform: translate(0, -50%);
transform: translate(0, -50%);
}
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/teddyrised/73xkT/7/
将孩子的位置从相对更改为绝对。
而不是margin-top使用top
.content header {
top: 50%;
position: absolute;
}
Run Code Online (Sandbox Code Playgroud)