Search code examples
htmlcssvertical-alignmenttext-align

Vertically align text with different font sizes


I have a jsfiddle here - http://jsfiddle.net/8bnLkyLv/

    <div class="alert">
        <p><i class="fa fa-exclamation-triangle"></i>This is some text</p>
    </div>

It's super simple, <p> tag that contains a <i> tag that containers a font awesome icon.

The <i> tag needs to be bigger than the text.

I need the text and the icon to be centered horizontally in the red container.

I know I could to it by absolutely positioning the <i> tag but that seems like a lot of messing for something so simple.


Solution

  • Simply give the bigger inline-level element - the <i> element in this case - a vertical-align of middle.

    .alert { background: red; font-family: sans-serif; text-align: center; }
    
    .alert p {
        color: white;
        display: inline-block;
        padding: 5px 0;
        vertical-align: center;
    }
    
    .alert p i {
        font-size: 2em;
        padding: 0 10px 0 0;
        vertical-align: middle; /* <-- Added declaration */
    }
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
    
    <div class="alert">
        <p>
            <i class="fa fa-exclamation-triangle"></i>
            This is some text
        </p>
    </div>