[英]margin top with percentage doesn't match the parent div
basically I'm trying to position an icon in the center of an inner div. 基本上,我试图将图标放置在内部div的中心。 In my code I have a div inside a div inside a div.
在我的代码中,我在div内的div内有一个div。 I would like the to center text in the innermost div so I tried using margin-top: 50% Instead, the text went further past the halfway point.
我想将文本放在最里面的div中心,所以我尝试使用margin-top:50%来代替,文本越过了中点。 I thought the innermost div would find the halfway point in the parent div and position accordingly.
我认为最里面的div会在父div中找到中点,并相应地定位。 Please explain why I am wrong.
请解释为什么我错了。 thx
谢谢
<html>
<body>
<div id="container" style="height:1000px;width:100%;background-color: green;position:absolute;">
<div id="inner" style="height:50%; width:50%; background-color: black;margin-top:50%;display:inline-block;">
<div id="inner" style="height:50%; width:50%; background-color: yellow"></div>
</div>
</div>
</body>
* { box-sizing: border-box; } .first { height: 500px; background-color: black; display: table-cell; width: 500px; text-align: center; vertical-align: middle; } .second { display: flex; justify-content: center; height: 300px; width: 300px; background-color: white; margin: 0 auto; } .third { align-self: center; height: 200px; width: 200px; background-color: green; padding: 25%; }
<div class='first'> <div class='second'> <div class='third'>Text is hereby centered!</div> </div> </div>
margin-top:50%
means that the top border of the element will be at the vertical half, which doesn't center the element. margin-top:50%
表示元素的顶部边框位于垂直的一半,而不是元素的中心。
To center that element it's best to use relative positions and display:block
for all elements, top:50%
, left: 50%
hich moves the upper left corner to the center of the parent, and in addition transform:translate(-50%, -50%)
, which moves it back (up and left) by half of its own height and width. 要使该元素居中,最好使用相对位置并对所有元素使用
display:block
, top:50%
, left: 50%
hich将左上角移到父元素的中心,另外transform:translate(-50%, -50%)
,将其向后(上下移动)自身高度和宽度的一半。
In addition the parent element has to have a defined height (which in your case is true). 此外,父元素必须具有定义的高度(在您的情况下为true)。 Here is a fiddle with the complete code:
这是完整代码的小提琴:
https://jsfiddle.net/49Lvzszj/1/ https://jsfiddle.net/49Lvzszj/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.