[html] How do I horizontally center an absolute positioned element inside a 100% width div?

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
}

This question is related to html css

The answer is


here is the best practiced method to center a div as position absolute

DEMO FIDDLE

code --

#header {
background:black;
height:90px;
width:100%;
position:relative; // you forgot this, this is very important
}

#logo {
background:red;
height:50px;
position:absolute;
width:50px;
margin: auto; // margin auto works just you need to put top left bottom right as 0
top:0;
bottom:0;
left:0;
right:0;
}

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.


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;
}

jsFiddle

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.


In my experience, the best way is right:0;, left:0; and margin:0 auto. This way if the div is wide then you aren't hindered by the left: 50%; that will offset your div which results in adding negative margins etc.

DEMO http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    margin:0 auto;
    right:0;
    left:0;
}

Its easy, just wrap it in a relative box like so:

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

The relative box has a margin: 0 Auto; and, important, a width...