Centering contents: Ghost element technique (Michał Czernow's hack)

by Fiddel

HTML

<div class="block">
  <div class="centered">1</div>
</div>

CSS

html, body {
	height:100%;
	width:100%;
}



/* This parent can be any width and height */
.block {
	
	height:50%;
  text-align: center;

  /* May want to do this if there is risk the container may be narrower than the element inside */
  white-space: nowrap;
	background-color:black;
}
 
/* The ghost element */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;

  /* There is a gap between ghost element and .centered,
  caused by space character rendered. Could be eliminated by
  nudging .centered (nudge distance depends on font family),
  or by zeroing font-size in .parent and resetting it back
  (probably to 1rem) in .centered. */
  margin-right: -0.25em;
	border:1px dotted black;
}

/* The element to be centered, can also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
  white-space: normal; /* Resetting inherited nowrap behavior */
	background-color:gold;
}