Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Vertically center align text in CSS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 471
    Comment on it

    Hello Readers.

    Center aligning text obviously gives it a more appealing look. Horizontal center align is what we do each day. But when it comes to vertical center align, things get a bit messed up. This too is easier with  a single word or a single line of text. There is a basic approach to this. We set the line-height of the text equal to the height of the containing box. The code is as follows :

    .box {
      height: 100px;
      line-height: 100px;
    }

    Works great!

    But then, this is limited to a single line of text.

    We want a solution for multiple lines of text that center aligns it, both horizontally and vertically. There is a fairly simple CSS solution for this as well. We will put to use CSS tables.

    We use display: table; to the parent div, which actually does not do much of a thing by itself. We will then set the text inside the span element to a display: table-cell; which allows us to use the vertical-align property on the specified text.

    HTML :

    <div>
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
    </div>

    CSS :

    div {
      display: table;
      width: 450px;
      height: 200px;
      text-align: center;
    }
    
    span {
      display: table-cell;
      vertical-align: middle;
    }

    But this may not work in certain browsers, specifically IE <= 7.

    Beautiful trick indeed!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: