Horizontal centering text over image via CSS

93,611

Solution 1

Try the following CSS:

.image {
    position:relative;
}

.text {
    left: 0;
    position:absolute;
    text-align:center;
    top: 30px;
    width: 100%
}

Solution 2

Try this:

.image {
    position:relative;
}

.text {
    position: absolute;
    top: 0;
    left: 0;
    width:100%;    
    height:100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
}

Solution 3

First you need to float the .image element, in order to 'collapse' its block-level descendants to the width of the element, and then use text-align on the .text element:

.image {
    float: left;
}
.text {
    text-align: center;
}

JS Fiddle demo.

Or you could simply give it a display: inline-block, which will allow it to have its block-level contents contained, and remain in the document flow:

.image {
    display: inline-block;
}
.text {
    text-align: center;
}

JS Fiddle demo.

Solution 4

Can you not use the image as the background image of the 'image' div using background-image: url('/yourUrl/'); and then rather than have your text in its own div simply place it in the image div and then apply text-align: center;

Share:
93,611

Related videos on Youtube

Zaur Nasibov
Author by

Zaur Nasibov

http://znasibov.info

Updated on February 09, 2022

Comments

  • Zaur Nasibov
    Zaur Nasibov about 2 years

    Consider the following html:

    <div class="image">
        <img src="sample.png"/>
        <div class="text">
           Text of variable length
        </div>
    </div>
    

    Where:

    .image {
        position:relative;
        text-align:center; // doesn't work as desired :(
    }
    
    .text {
        position:absolute;
        top:30px;
    }
    

    Can you please tell, if there is a way to horizontally align the text in the center of the .image div? I can't use the left property, since the length of the text is unknown and the text-align property doesn't work for the .text div :(

    Thank you.

  • Dani
    Dani over 7 years
    Just a variation of @MyHeadHurts link, hopefully to give you ideas of what can be done.
  • GabLeRoux
    GabLeRoux about 7 years
    One can play with the following example: jsbin.com/docoma/1/edit?html,css,output
  • Pete
    Pete almost 6 years
    If you use flex, why not just swap the order using order rather than using an absolute positioning hack