Grow your CSS skills. Land your dream job.

Simple vertical alignment solution

  • # January 6, 2010 at 2:43 pm

    My boss asked me to make same area always stay vertical centered regardless how much text was in the box. I know we tend to cringe when vertical alignment comes up but it sounded like a fun challenge. Since it has plagued me I thought I would throw up this tip/trick to anyone else trying to get the same result. note: I know you can use other elements besides div here. I’m just using div for the example.

    HTML

    Code:
    Title Shown Here
    Text shown. Use multiple lines as you please.

    CSS (concept could work with or without a pre-defined height)

    Code:
    #container
    {
    background-color: red;
    color: #ffffff;
    width: 300px;
    height: 400px;
    }

    #title
    {
    font-size: 1.8em;
    }

    #text
    {
    font-weight: bold;
    }

    Jquery

    Code:
    $(function()
    {
    var titleHeight = $(‘#title’).height();
    var textHeight = $(‘#text’).height();
    var containerHeight = $(‘#container’).height();
    var dynamicPadding = (containerHeight-(titleHeight + textHeight))/2;

    $(‘#container’).css({‘padding-top':dynamicPadding+’px’});
    });

    This forces the the title and text to be directly center every time. I’m sure others have used this concept but thought I would share. it works great and I haven’t had any odd issues with it.

    Let me know what you guys think about this concept.

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".