I have a div that is absolute positioned (because it holds sub-divs that are themselves absolutely positioned), that I want horizontally centered.
I can achieve that using the following CSS
width : 512px;
position : absolute;
left : 50%;
margin-left :-256px; // half width of div
(complete test in http://jsbin.com/eruwep/2/edit)
However when the window isn’t large enough, the div overflows to the left.
Is there a way to have it centered when the page is large enough, but left-justified otherwise (using just CSS)?
Why are you using
position: absolutefor the container? If it’s just because you want its absolutely positioned children to be positioned relative to their container, you don’t needabsolutefor that. Any value other thanstaticwill do that.Changing the CSS you mentioned in your question to the following will make it work:
Example in: http://jsbin.com/eruwep/3/edit