Henry Yun
Henry Yun

Reputation: 544

Center a child <div> to the screen width, not the parent <div>

There is a narrow DIV which contains a much wider DIV. How do I center the child DIV horizontally within the browser window (and not the parent DIV) such that the left and right margins are equal?

<div id="narrow_container" style="float:left;">
     <div id="wide_contents">
     </div>
</div>

Upvotes: 1

Views: 4049

Answers (1)

Herman Schaaf
Herman Schaaf

Reputation: 48475

Possible CSS:

<style>
#narrow_container {display: block; 
   width: 600px; 
   margin: 0 auto;
} /* narrow div, this can be anything except position: relative */
#wide_contents {position: absolute;  
   width:400px;
   margin-left:-200px; 
   left:50%; 
} /* screen-centered div */
</style>

You're basically then just positioning the element absolutely relative to the window, since absolute positioning positions relative to the closest parent with position: relative. If you don't have any parents with position: relative, it will default to the document body.

The technique for centering is reasonably common and makes use of a negative margin that is as wide as half of element's width, and then positions the element 50% from the left. This results in a horizontally centered element.

Upvotes: 1

Related Questions