30 seconds of CSS

  Back to Home

Ghost trick  layout

Vertically centers an element in another.

HTML
<div class="ghost-trick">
  <div class="ghosting"><p>Vertically centered without changing the position property.</p></div>
</div>
CSS
.ghosting {
  height: 300px;
  background: #0ff;
}

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

p {
  display: inline-block;
  vertical-align: middle;
}
Demo

Vertically centered without changing the position property.

Explanation
  • Use the style of a :before pseudo-element to vertically align inline elements without changing their position property.
Browser support

100.0%