Search code examples
javascriptjquerycsspositioning

Center absolute div indside/outside relative div


Is it possible with either CSS or jQuery to center an absolute div inside or outside a relative div, if you dont know the width of the relative div witch in this case is the parent element of the two.

normally i would do something like:

.child {
position: absolute;
top: 100%;
left: -50px;
width: 200px;
height: 300px;
}

but only if i knew that the parent is 100px wide, but what if i dont know?

FIDDLE


Solution

  • If you don't need to target IE8 and lower, you can use the CSS3 calc() function:

    left: calc(50% - 100px);

    Replace 100px with half of whatever width your absolute positioned child element is.

    JSFiddle example: http://jsfiddle.net/Gmmqh/5/

    Note the use of box-sizing: border-box to make the boxes even with each other, like on the third one.