N ways to vertically center elements

First way with line-height (not sure about cross-browser)

HTML:

<div id="header"><div class="center">header</div></div>

CSS:

#header {
  height: 100px;
  background: gray;
  text-align: center;
  line-height: 100px;
}

Second way, negative margins

#header {
  background: gray;
  position: relative;
  height: 100px;
  text-align: center;
}

.center {
  background: pink;
  position: absolute;
  width: 20px;
  height: 20px;
  top: 50%;
  left: 50%;
  margin-left: -10px;
  margin-top: -10px;
}

Third way, display:table with display:table-cell.

#header {
  display: table;
  height: 100px;
}

.center {
  display: table-cell;
  vertical-align: middle;
}

Third way to align both vertically and horizontally.

#header {
  display: table;
  height: 100px;
  width: 100%;
}

.center {
  display: table-cell;
  vertical-align: middle;
  width: 100%;
  text-align: center;
}

Further read: http://www.vanseodesign.com/css/vertical-centering/

Advertisements
Standard