Horizontal centering text over image via CSS
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;
}
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;
}
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;
Related videos on Youtube
Comments
-
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 theleft
property, since the length of the text is unknown and thetext-align
property doesn't work for the.text
div :(Thank you.
-
Dani over 7 yearsJust a variation of @MyHeadHurts link, hopefully to give you ideas of what can be done.
-
GabLeRoux about 7 yearsOne can play with the following example: jsbin.com/docoma/1/edit?html,css,output
-
Pete almost 6 yearsIf you use flex, why not just swap the order using
order
rather than using an absolute positioning hack