Eric Grange
Eric Grange

Reputation: 6211

Horizontally centering an absolute div that will align to the left when screen isn't large enough

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)?

Upvotes: 0

Views: 110

Answers (2)

mercator
mercator

Reputation: 28656

Why are you using position: absolute for the container? If it's just because you want its absolutely positioned children to be positioned relative to their container, you don't need absolute for that. Any value other than static will do that.

Changing the CSS you mentioned in your question to the following will make it work:

width : 512px;
position : relative;
margin : auto;

Example in: http://jsbin.com/eruwep/3/edit

Upvotes: 1

Andy
Andy

Reputation: 14575

You could try media queries: http://jsfiddle.net/RfUZj/

Upvotes: 1

Related Questions