Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does margin: auto only work horizontally and not vertically?

Tags:

html

css

margin

I have seen that while developing websites, vertically centering a container (of fixed height) inside a container of random height always comes as a nightmare for the web developer (at least, me) while when it comes to horizontal centering a container (of fixed width) inside a container of random width, the margin:0px auto; tends to serve an easy way out in the standard model.

When things can be as simple as that why doesn't CSS work out with the margin:auto 0px; when it comes to centering a container of fixed height inside a container of random height? Is there any specific reason to do so?

like image 963
ikartik90 Avatar asked Dec 23 '11 20:12

ikartik90


People also ask

What happens when you set margin to auto?

The auto Value You 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.

What is needed for margin 0 Auto to work?

The element must be block-level, e.g. display: block or display: table. The element must not float. The element must not have a fixed or absolute position.


2 Answers

It's really less of a nightmare than you think, just don't use margins. vertical-align is really what you should rely on for fluid-height vertical centering. I threw together a quick demo to demonstrate my point:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
  text-align: center;
}

span {
  height: 100%;
  vertical-align: middle;
  display: inline-block;
}

#any-height {
  background: #000;
  text-align: left;
  width: 200px;
  height: 200px;
  vertical-align: middle;
  display: inline-block;
}
<span></span>
<div id="any-height"></div>

See: http://jsfiddle.net/Wexcode/jLXMS/

like image 133
Wex Avatar answered Sep 20 '22 15:09

Wex


The right answer for your question is that margin: auto 0 doesn't work the same way that margin: 0 auto works because width: auto doesn't work the same way height: auto does.

Vertical auto margin works for absolutely positioned elements with a known height.

.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    width: 150px;
    height: 150px;
    margin: auto;
}
like image 26
user1602599 Avatar answered Sep 19 '22 15:09

user1602599