Wednesday, October 10, 2012

Vertical centering text with CSS

Nowadays I get a lot of designs with vertically centered text in it. Sometimes the text is only a word but it can be multiple lines long too. The problem was, I could not determine, wether the printed text will be broken into multiple lines or not. Luckily, I have found a solution to this problem in pure CSS. This is instantly added to my sitebuilding template for future use.

Here is a little demo showing how it works:
http://cssdesk.com/K36px


Let's see the code:

HTML


1
2
3
4
5
<div class="outer">
   <div class="inner">
      <div class="element">Centered</div>
   </div>
</div>


Default CSS



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.outer {
  display: table;
   height: 155px;
   overflow: hidden;
   width: 980px;
}

   .outer .inner {
      display: table-cell;
      vertical-align: middle;
      width: 100%;
      margin: 0 auto;
   }



CSS for IE


1
2
3
.outer { position: relative; }
.outer .inner { position: absolute; top: 50%; }
.outer .inner .element { position: relative; top: -50%; }

No comments:

Post a Comment