CSS - 保证金最高50%超过50%

时间:2013-12-14 16:41:24

标签: html css

我希望通过百分比获得带有操作边际的子div。 y位置应为父div的50%。但它在某种程度上更多。为什么不是50%?

js fiddle

HTML

<div class="content">
  <header></header>
</div>

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;
}

2 个答案:

答案 0 :(得分:16)

这是因为当以百分比表示顶部/底部边距和填充时,这些值将被视为父元素的小数宽度,而不是高度。根据{{​​3}}:

  

[margin]百分比是根据宽度计算的   生成的框包含块。请注意,这是真的   'margin-top'和'margin-bottom'也是如此。如果包含块的话   width取决于此元素,然后生成的布局未定义   在CSS 2.1中。

此问题之前已在StackOverflow中解决 - W3C definition


建议:如果您想要将元素垂直放置在中心,可以使用以下技巧:

  1. 绝对定位子元素
  2. 声明父级的维度,使父级的维度不依赖于子级维度
  3. 将子元素从顶部放置50%
  4. 使用CSS 2D翻译的漂亮技巧。
  5. 以下是您小提琴中经过修改的CSS:

    .content header {
        width: 100px;
        height: 100px;
        top: 50%;
        background: red;
        position: absolute;
        -webkit-transform: translate(0, -50%);
        transform: translate(0, -50%);
    }
    

    see here

答案 1 :(得分:4)

将孩子的position从相对变为绝对。
而不是margin-top使用top

http://jsfiddle.net/73xkT/5/

.content header {
  top: 50%;
  position: absolute;
}
相关问题