html – CSS – 保证金最高50%超过50%

我想要一个通过百分比的op-margin的子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;
}

解决方法

这是因为当以百分比形式显示顶部/底部边距和填充时,这些值将被视为父元素的小数宽度,而不是高度.根据 W3C definition

The [margin] percentage is calculated with respect to the width of the
generated Box’s containing block. Note that this is true for
‘margin-top’ and ‘margin-bottom’ as well. If the containing block’s
width depends on this element,then the resulting layout is undefined
in CSS 2.1.

此问题之前已在StackOverflow – see here中得到解决.

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

>绝对定位子元素
>声明父级的维度,使父级的维度不依赖于子级的维度
>将子元素从顶部放置50%
>使用CSS 2D翻译的漂亮技巧.

这是你的小提琴中修改过的CSS有效:

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

http://jsfiddle.net/teddyrised/73xkT/7/

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些