[英]How to Center Child with Absolute Position
I have two div's inside another div, and I want to center child div.So,Please How can I do this?我在另一个 div 中有两个 div,我想将子 div 居中。所以,请问我该怎么做?
#father {
position: relative;
}
#son1 {
position: absolute;
width:285px;
}
#son2 {
position: absolute;
width:285px;
}
First, you set a 50% left to the child element.首先,您为子元素设置了 50% 的左侧。 Now the left side of the child element is at the middle of it's parent element.
现在子元素的左侧位于其父元素的中间。 So, in order to bring the child's element center at it's parent center, set a negative left margin of it's half width (285 / 2 = 142.5).
因此,为了将子元素的中心置于其父中心,请设置其半宽的负左边距 (285 / 2 = 142.5)。 Sorry for my english!
对不起我的英语不好!
#son1, #son2 {
position: absolute;
left: 50%;
margin-left: -142.5px;
}
EDIT编辑
In order to center the child elements inside their parent element, and have the child elements next to each other check this:为了将子元素置于其父元素内,并使子元素彼此相邻,请检查以下内容:
#father { width: 100%; height: 200px; position: relative; padding-top: 50px; background-color: #ccc; } #child-wrapper { width: 580px; position: absolute; left: 50%; margin-left: -290px; } #child-wrapper > div:first-child { margin-right: 10px; } #child-wrapper > div { background: #f1f1f1; } #son1, #son2 { width: 285px; padding: 20px 0; float: left; text-align: center; }
<div id="father"> <div id="child-wrapper"> <div id="son1">Son1</div> <div id="son2">Son2</div> </div> </div>
#son1, #son2
{
position: absolute;
left: 50%;
margin-left: -50%;
}
Yes you can you have to set top and left with margin-top and margin-left是的,您可以使用 margin-top 和 margin-left 设置顶部和左侧
You can check code here你可以在这里检查代码
#father { position: relative; background: green; height:150px; width:300px; } #son1 { position: absolute; width:100px; margin-left:-50px; /* -half of width */ height:50px; background: yellow; left:50%; top:50%; margin-top:-25px; /* -half of height*/ } #son2 { position: absolute; width:50px; margin-left:-25px; /* -half of width */ height:30px; background: red; left:50%; top:50%; margin-top:-15px; /* -half of height*/ }
<div id="father"> <div id="son1"></div> <div id="son2"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.