Skip to main content
1 de 2
Marta
  • 1,4mil
  • 12
  • 15

Eu não vi, entre as respostas, a minha solução favorita:

HTML

<div class="block">    
    <div class="centered">
    <h1>Some text</h1>
    <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
</div>  
</div>

CSS

/* This parent can be any width and height */
.block {
  text-align: center;
}
 
/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

Via http://css-tricks.com/centering-in-the-unknown/

Gosto dessa solução porque usando o :after o código fica limpo, eu posso usar as tags que forem mais semânticas para o caso e nunca tive problemas. O :before funciona a partir do IE8.

Marta
  • 1,4mil
  • 12
  • 15