CodePen

HTML

            
              <h1>Center to middle tricks</h1>
<p>:hover increases child size so you can verify how dynamic each method is.</p>
<h2>Trick 1: line-height</h2>
<div class="line-height">
  <span>1</span>
</div>
<p>Good: very dynamic. Bad: you need to know maximum height the child so you can set line-height accordingly. Firefox' vertical alignment is slightly off.</p>

<h2>Trick 2: display as table-cell</h2>
<div class="table">
  <span>2</span>
</div>
<p>Good: can center any kind of content to middle. Bad: parent needs extra wrapper element if you want to center it.</p>

<h2>Trick 3: absolute position</h2>
<div class="absolute">
  <span>3</span>
</div>
<p>Good: can break out of parent. Bad: can break out of parent and you need to define exact measurements of the child element so this is very limited.</p>

<h2>Trick 4: pseudo inline element</h2>
<div class="pseudo">
  <span>4</span>
</div>
<p>Good: fully dynamic, no line-height limitation. Bad: <code>font-size: 0;</code> can be troublesome. Lengthy code.</p>
            
          
!

CSS

            
              html {
  background: white;
}

body {
  background: #EEE;
  margin: 0 auto;
  padding: 1em;
  width: 30em;
}

h2 {
  background: #DDD;
  margin: .5em -.5em;
  padding: .5em;
}

/* shared styles */
div {
  background: green;
  height: 100px;
  width: 100px;
}

span {
  background: #CFC;
  box-shadow: 0 0 0 1px black;
  font-size: 32pt;
  height: 50px;
  width: 50px;
  text-align: left;
}

span:hover {
  padding: 20px;
}

/* minimum styles required for the effect */
.line-height {
  line-height: 100px;
  text-align: center;
}

.line-height span {
  display: inline-block;
  line-height: normal;
  vertical-align: middle;
}

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

.table span {
  display: block;
  margin: 0 auto;
}

.absolute {
  position: relative;
}

.absolute span {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -25px;
  margin-top: -25px;
}

.pseudo {
  font-size: 0;
  position: relative;
  text-align: center;
}

.pseudo:before {
  content: '';
  display: inline-block;
  height: 100%;
  width: 0;
  vertical-align: middle;
}

.pseudo span {
  display: inline-block;
  vertical-align: middle;
}
            
          
!
? ?
? ?
Must be a valid URL.
+ add another resource
via CSS Lint

JS

            
              
            
          
!
Must be a valid URL.
+ add another resource
via JS Hint
Loading ..................