Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is width necessary when centering a div with margin auto?

Tags:

html

css

I tried to center my div using margin: auto like this:

#main-container #control-panel {margin: 10px auto;}

But it still align to the left. I found that I have to specify a width for the div so that it will get centered:

#main-container #control-panel {width: 300px; margin: 10px auto;}

So, is width necessary for centering a div? I thought the width of div should be automatically modified by its inner content? (In this case, I have a button inside the control-panel div)

The result is tested under latest Chrome.

like image 789
clwen Avatar asked Oct 23 '25 15:10

clwen


2 Answers

Yes, it's necessary.

The default value for the width of a div is auto, which means that it will try to take up all available space horisontally. As that leaves no margins on the sides, the automatic margins will be zero.

like image 183
Guffa Avatar answered Oct 25 '25 15:10

Guffa


Yes, you have to define width to your div if you want him in center

But in case you didn't want fixed width then just define text-align:center in parent div & define display:inline-block to it like this:

.parent{
 text-align:center;
} 

.child{
 display:inline-block;
 text-align:left;
}

check this http://jsfiddle.net/sandeep/HzuYv/

like image 27
sandeep Avatar answered Oct 25 '25 14:10

sandeep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!