1

You can easy set width to auto with margin:0px, auto

#container{
  background-color: blue;
  height:600px;
  width:600px;
  margin:0px auto; }
<div id="container"></div>

But why can't you set height to auto with margin:auto 0px? I mean, Why doesn't margin: auto 0px; vertically center a block as margin: 0px auto; horizontally centers it?

#container{
  background-color: blue;
  height:600px;
  width:600px;
  margin:0 auto; }
<div id="container"></div>
  • 3
    I'm not sure what you're asking, but your css is incorrect in your second snippet. You have a comma between `0px` and `auto` – entropic Oct 27 '14 at 02:08
  • The question seems to be, "*Why doesn't `margin: auto 0px;` vertically center a block as `margin: 0px auto;` horizontally centers it?*" For that, "[Using margin:auto to vertically align div](http://stackoverflow.com/questions/12415661/using-marginauto-to-vertically-align-div)" provides an explanation. – Jonathan Lonowski Oct 27 '14 at 02:18
  • @JonathanLonowski Thanks, that's what I mean. I have updated the question to make it clear. – Ave Maleficum Oct 27 '14 at 02:21

2 Answers2

1

How to accomplish a centered vertical-align depends on what exactly you'd like to do.

With block level elements, each div/box/etc is stacked left to right and then top to bottom. A good explanation of block elements can be found here and another one here on the MDN. Here is an in-depth look at the display property.

misterManSam
  • 24,303
  • 11
  • 69
  • 89
  • 1
    There are better resources than w3schools - [Block elements (MDN)](https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements) / [Inline elements (MDN)](https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elemente) / [The display property (CSS Tricks)](http://css-tricks.com/almanac/properties/d/display/). [Here is a very good technique to vertically center with an in-depth explanation.](http://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/) – misterManSam Oct 27 '14 at 04:19
  • Thanks for adding that! I was blocked from leaving more links because I haven't left very many answers. – Richard Czechowski Oct 27 '14 at 05:01
  • 1
    Oh, didn't think about that. I have added them all to your answer; I think you should be able to edit the wording now, if you want, and still keep the links active. :) – misterManSam Oct 27 '14 at 05:10
  • 1
    Also, it would be even better if you could add a small snippet of HTML / CSS for each of those techniques that are linked. When you answer a question, think: "if these links go dead, is my answer still helpful?" – misterManSam Oct 27 '14 at 05:15
  • Will do. Thanks for the tips! – Richard Czechowski Oct 27 '14 at 06:15
-1

You seem to have a syntax error. It should be:

margin: 0 auto;

Take out the 'px' and remove the comma.

c0deNinja
  • 3,956
  • 1
  • 29
  • 45
user3681587
  • 566
  • 5
  • 12