gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:41:20 25 4
gpt4 key购买 nike

我想要一个带有百分比操作边距的子 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com