deruse
deruse

Reputation: 2881

trying to center a div inside a fixed-width div

I have a parent div whose width is fixed at 150px. When I create a child div, firebug says its width is 150px too. Why is this?

Thus, when I try to use margin auto to horizontal align the div, it doesn't make a difference. Is there any way to override the 150px width that is automatically set for the child div?

Upvotes: 0

Views: 744

Answers (3)

doyoe
doyoe

Reputation: 302

Because div is a block level element, the default width of the full parent. The width of an inline element content itself adaptive, for example: span element

Upvotes: 1

fordareh
fordareh

Reputation: 2963

@j08691 is right about div's being block elements. You'll either need stylesheet or inline styles that have the following effect:

<div style="width: 150px; text-align: center;">
  <div style="width: [smaller width]; margin: 0 auto; text-align: left;"></div>
</div>

..the reason is that the inner div's margin can't automatically determine their size unless the inner div has a width.

[...the text-align stuff is just left over sludge from back in the IE6 (and 7?) days ;-) ]

Upvotes: 0

j08691
j08691

Reputation: 207861

A div by default is a block element and block elements take up the full width of their containing element unless otherwise specified.

Upvotes: 3

Related Questions