I have two div's inside another div, and I want to center child div.So,Please How can I do this?
#father {
position: relative;
}
#son1 {
position: absolute;
width:285px;
}
#son2 {
position: absolute;
width:285px;
}
I have two div's inside another div, and I want to center child div.So,Please How can I do this?
#father {
position: relative;
}
#son1 {
position: absolute;
width:285px;
}
#son2 {
position: absolute;
width:285px;
}
Share
Improve this question
edited Nov 25, 2014 at 12:47
Brian Mains
50.7k35 gold badges155 silver badges260 bronze badges
asked Nov 25, 2014 at 12:45
Charnjeet SinghCharnjeet Singh
3,1077 gold badges38 silver badges65 bronze badges
11
- Can you share the HTML markup too please? – web-tiki Commented Nov 25, 2014 at 12:47
- 1 center horizontally? vertically? both? – Roi Commented Nov 25, 2014 at 12:47
-
top: 0; right: 0; left: 0; bottom: 0; margin: auto;
- Put this on the absolute positioned elements and it will center. – Ruddy Commented Nov 25, 2014 at 12:52 - @Ruddy this centers only horizontally untill the OP add some height for his div though he has the width mentioned already. No hard feelings – Benjamin Commented Nov 25, 2014 at 12:54
- 1 @Ruddy yep I agree that. – Benjamin Commented Nov 25, 2014 at 12:58
3 Answers
Reset to default 5First, you set a 50% left to the child element. 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). 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
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>