First things first, each of the elements above are blocks and have set margin: 0 auto, but it does not work since blocks have width equal to 100% by default (the first example). The block covers the whole page and therefore cannot be centered.
So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered.
The auto ValueYou can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
margin:0 auto; 0 is for top-bottom and auto for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container. Generally if you want to put any element at center position then margin:auto works perfectly.
Off the top of my head:
display: block
or display: table
Off the top of other people's heads:
width
that is not auto
2
Note that all of these conditions must be true of the element being centered for it to work.
1There is one exception to this: if your fixed or absolutely positioned element has left: 0; right: 0
, it will center with auto margins.
2Technically, margin: 0 auto
does work with an auto width, but the auto width takes precedence over the auto margins, and the auto margins are zeroed out as a result, making it seem as though they "don't work".
Off the top of my head, it needs a width
. You need to specify the width of the container you are centering (not the parent width).
Complete rule for CSS:
display: block
AND width
not auto) OR display: table
float: none
position: relative
OR position: static
OR
display: flex
Off the top of my cat's head, make sure the div
you're trying to center is not set to width: 100%
.
If it is, then the rules set on the child divs are what will matter.
Off the top of my head, if the element is not a block element - make it so.
and then give it a width.
It will also work with display:table - a useful display property in this case because it doesn't require a width to be set. (I know this post is 5 years old, but it's still relevant to passers-by ;)
Please go to this quick example I've created jsFiddle. Hopefull it's easy to understand. You can use a wrapper
div with the width of the site to center align. The reason you must put width
is that so browser knows you are not going for a liquid layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With