Search code examples
htmlimagetextalignment

Adding text over an image in the middle


I want to add some text over an image in the middle. I use this code:

<div style="background-image: url(../images/game-hearts-icon.png); height: 64px; width: 64px; text-align: center; vertical-align:middle;">text</div> 

I want the text to be in the middle of the heart. But it just appears in the top centered. The vertical alignment doesn't seem to be working. What am I doing wrong? Any help appreciated!


Solution

  • Set the line-height to equal the height of your div:

    <div style="background-image: url(../images/game-hearts-icon.png); height: 64px; width: 64px; text-align: center; line-height: 64px;">text</div>
    

    Better yet, don't use inline styles:

    HTML

    <div class="game-hearts-icon">text</div>
    

    CSS

    .game-hearts-icon {
        background: transparent url(../images/game-hearts-icon.png) scroll 0 0 no-repeat;
        height: 64px;
        line-height: 64px;
        text-align: center;
        width: 64px;
    }