CSS - 50%的毛利率超过50% [英] CSS - margin top of 50% is more than 50%

查看:107
本文介绍了CSS - 50%的毛利率超过50%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个具有运算余量百分比的子div。 y位置应为父div的50%。但它是不知何故更多。为什么不是50%?

I want a child div with a op-margin via percentage. The y-position shall be 50% percent of the parent div. But it is somehow more. Why isn't it 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;
}


推荐答案

到顶部/底部边距和paddings百分比,这些值将被作为父元素的分数宽度,而不是高度。根据 W3C定义

This is because when it comes to top/bottom margins and paddings in percentages, the values will be taken as the fractional width of the parent element, not the height. According to the W3C definition:


[margin]百分比是相对于
生成框的包含块的宽度计算的。注意,这也适用于
'margin-top'和'margin-bottom'。如果包含块的
宽度取决于这个元素,那么结果布局在CSS 2.1中是未定义的

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中解决,请参阅此处

This question has been addressed before in StackOverflow - see here.

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

Suggestion: If you would want to position an element in the center vertically, you can use the following trick instead:


  1. 绝对定位子元素

  2. 声明父元素的尺寸,使父元素的尺寸不依赖于子元素的尺寸

  3. 将子元素从顶部定位50%

  4. 使用CSS 2D翻译的奇妙技巧。

  1. Position the child element absolutely
  2. Declare dimensions for the parent, such that the parent's dimensions do not rely on those of the child
  3. Position the child element 50% from the top
  4. Use a nifty trick of CSS 2D translation.

这是从你的小提琴修改的CSS工作原理:

Here's the modified CSS from your fiddle that works:

.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/

这篇关于CSS - 50%的毛利率超过50%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆