Why margin: auto doesn't work in this case?

Why margin: auto doesn't work in this case?


pen: [ http://codepen.io/ustvarno/pen/yJWJox?editors=0100 ]

margin code:
#content {

    position: relative;
    display: block;
    width: $width;
    height: $height;
    margin:  auto;

also i set width and height on parent tag ( body and his parent html )


The square is centered, so it works, right? Or did I miss something?


Works fine for me. If you mean to have it vertically centered as well, that’s a bit more challenging. You’ll need absolute positioning or flexbox. I can write up code for that if that’s the purpose.

Otherwise just give a margin top attribute to your container to get some space between it and the boundary.


Do u mean centered both horiz and vertic?
For me it is just horizontal centered

Why it is challenging, look from browser side i give him height of parent ( body, html ) and also height of self, and he just need to center it, nothing magically to do?


Oh, you also meant vertically centered? Then you’ll have to do as @imtoobose said. It’s more challenging than horizontal centering because margin: auto; alone won’t be enough. I used to do it with absolute positioning (which can get complicated), but now I use flexbox.


Web Pages are meant to be read top to bottom. Unless you have a static page that never scrolls (like the weather app) or some small app, you definitely don’t want or need vertical centering. That being said, here are two ways of doing it.

One: Set the parent’s position as relative, unless the parent is the body, in which case it’s fine if you don’t. In the child you want vertically centered put the following CSS:

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

Note that transform is supported by most browsers but you’ll need the proper vendor prefixes.
The better way is to use flexbox:

  display: flex;
  justify-content: center;
  align-items: center;

  flex: 1 0 1;

Very useful reference for flex box: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
This is my go to guide for whenever I forget how something in flex works, or what it can (and cannot) do. Read through it, it’s worth it.