Skip to content Skip to sidebar Skip to footer

Center Span/text Vertically Inside H1

I'd like to center a span element inside a h1 tag. I tried to to set a line-height but it seems to center only the span but not the text next to it. Note: I probably can't use posi

Solution 1:

Your CSS basically works. It is more obvious if you increase the line-height:

see demo at http://jsfiddle.net/audetwebdesign/PUeaY/

h1 {
    background: red;
    font-size: 40px;
    line-height: 80px;
}
.icon {
    background: aqua;
    border: 1px solid blue;
    border-radius: 3px;
    padding: 0px4px;
    width: auto;
    display: inline-block;
    font-size: 20px;
    line-height: 40px;
    vertical-align: 7px;
}

In this example, both the span and the text are vertically aligned in the center, which I think is what you want.

How This Works...

The CSS engine uses the vertical-align property to align the baseline of the text segments.

In this case, I set the default font-size and line-height for h1 to 40px and 80px respectively.

For the .icon, I reduce the font-size and line-height by 50%. If vertical-align were set to baseline or 0, both the smaller and the larger text would align along the bottom of the letters, but it would not look centered because the icon text has a smaller font size.

By adjusting vertical-align to 7px, I got a centering that looks pretty good. This is not exactly a precise process, but it may work well enough.

Solution 2:

Another easy way to achieve this would be to use negative margins.

span{margin:-4px10px00} // Uses order of top, right, bottom, left

Post a Comment for "Center Span/text Vertically Inside H1"