How do I horizontally center an absolute positioned element inside a 100% width div? [duplicate]
In the example below, #logo
is positioned absolutely and I need it to be horizontally centered within #header
. Normally, I would do a margin:0 auto
for relatively positioned elements but I am stuck here. Can someone show me the way?
JS Fiddle: http://jsfiddle.net/DeTJH/
HTML
<div id="header">
<div id="logo"></div>
</div>
CSS
#header {
background:black;
height:50px;
width:100%;
}
#logo {
background:red;
height:50px;
position:absolute;
width:50px
}
Solution 1:
If you want to align center on left attribute.
The same thing is for top alignment, you could use margin-top: (width/2 of your div), the concept is the same of left attribute.
It's important to set header element to position:relative.
try this:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left:50%;
margin-left:-25px;
}
DEMO
If you would like to not use calculations you can do this:
#logo {
background:red;
width:50px;
height:50px;
position:absolute;
left: 0;
right: 0;
margin: 0 auto;
}
DEMO2
Solution 2:
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
Solution 3:
Was missing the use of calc
in the answers, which is a cleaner solution.
#logo {
position: absolute;
left: calc(50% - 25px);
height: 50px;
width: 50px;
background: red;
}
Works in most modern browsers: http://caniuse.com/calc
Maybe it's too soon to use it without a fallback, but I thought maybe for future visitors it would be helpful.