Jack
Jack

Reputation: 1

Inline CSS Not Centering <div>

I have read other questions on stackoverflow about centering and have used this technique before.

I tried using:

<div style="width: 1000px; position: absolute; margin: 300px auto 0px auto;">
content in here
</div>

This did not center the div. What have I done wrong? I feel like I have used this code before, but it will not work this time. I tried making a new html file, and I tried it in case I had done something wrong on this particular page. It was flawed as well. How is it wrong?

Upvotes: 0

Views: 305

Answers (2)

Ben Rowe
Ben Rowe

Reputation: 28691

The auto margin trick doesn't work for elements that have absolute positioning. Try the following instead:

width: 1000px;
position: absolute;
top: 300px;
left: 50%;
margin-left: -500px;

This works by centring the LHS of the element using left: 50% then centering the element by using a negative margin of exactly half it's width.

Upvotes: 0

alex
alex

Reputation: 490153

Get rid of position: absolute.

jsFiddle.

BTW, it as nothing to do with the fact the styles are inline.

Upvotes: 2

Related Questions