html - CSS - margin top of 50% 超过 50%

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

最佳答案

这是因为当涉及到顶部/底部边距和填充百分比时,这些值将被视为父元素的小数宽度,而不是高度。根据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 .


建议:如果你想将一个元素垂直放置在中心,你可以使用下面的技巧:

  1. 绝对定位子元素
  2. 为父级声明维度,这样父级的维度不依赖于子级的维度
  3. 将子元素定位在距顶部 50% 的位置
  4. 使用 CSS 2D 转换的绝妙技巧。

这是从你的 fiddle 中修改后的有效 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/

关于html - CSS - margin top of 50% 超过 50%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20585682/

相关文章:

html - 为什么我无法在表单后的导航栏上保留任何内容?

html - 展示页面的 Facebook Like 按钮对话框

css - 无法正确对齐我的 CSS 菜单

css - Chrome/Safari 中的图像插值模式?

html - Flexbox 在 IE 或 Chrome 中无法正确显示

html - 文本底部与图像完全对齐

javascript - 整个队列的 SWFUpload 进度条

javascript - replaceWith() 在 .hover() 中不起作用

jquery - 单击菜单上的 Bootstrap 向上滚动,单击时

html - CSS '' background-color“属性不适用于 <div> 内的复选框