1001st vertical alignment method

    Much has been said about the vertical alignment of a block of unknown height in the center or bottom of the parent. There are methods based on display: table-cell for good browsers (without quotes) and expression for IE, methods based on relative positioning (may not work well when overflowing). This article will describe a method that works on the features of such a powerful display as the built-in block (display: inline-block).

    screen-capture


    Markup



    Immediately make a reservation, the method has a drawback, namely, an extra element. The markup will look like the one shown below: The described method is based on the fact that vertical-align: middle works fine for inline elements. Since in our case inline elements will not work, a mixed type (display: inline-block) is used to emulate them. Thus, if we manage to present the inner contents of div.parent as a string, and div.child in it to center, using vertical-align: middle, then we will achieve the result.

        
    Текст, который заключён во внутренний блок.

        







    Styles



    The first idea that arises - to force the height of the line of internal content using line-height to 100% of the height of the div.parent - disappears, because entails changing the height of the line inside the div.child, and redefining the line-height inside the div.child does not lead to a positive result. The same strut from the 90s comes to the rescue. The added Div.helper block should have the height div.parent, thereby spreading our line as we need. As a result, significant CSS can be highlighted:

    .child {
        ...
        display:inline-block;
        vertical-align:middle;
    }
    .helper {
        ...
        display:inline-block;
        vertical-align:middle;
        height:100%;
        width:0px;
    }



    Fighting IE



    We use a hack for IE, which allows us to use display: inline-block for block elements (as well as a hack for FF2):

    .child {
        ...
        display:-moz-inline-box;
        display:inline-block;
        vertical-align:middle;
        zoom:1;
        //display:inline;
    }
    .helper {
        ...
        display:-moz-inline-box;
        display:inline-block;
        vertical-align:middle;
        height:100%;
        width:0px;
        zoom:1;
        //display:inline;
    }



    Result



    Here is such a simple way. A working example can be found here .

    Also popular now: