obautista obautista - 10 months ago 54
CSS Question

Center text inside image dynamically

I have a container div where height and width are set to 100% and position is relative. Inside the div I center an image (image is smaller than div) using display: block and margin:auto. Then I am attempting to center text inside the image using position: absolute, left: 45%, top 82px. Vertical alignment appears to be okay, but as the number of characters in text grows the text is no longer aligned in the middle. So in my image below if text is 4 characters the text would no longer be centered. Is there a better way to dynamically align text?

enter image description here


<div id="countup-container">
<img id="countup-image" src="/_layouts/Images/abc/free.png" alt="Free">
<span id="ctl00" class="countup-text">101</span>

Relevant CSS:

#countup-container {
height: 100%;
width: 100%;
position: relative;

#countup-image {
display: block;
margin: auto;
width: 300px;
height: 240px;

.countup-text {
z-index: 100;
position: absolute;
color: black;
font-size: 40px;
font-weight: bold;
left: 45.3%;
top: 82px;

Answer Source

If you are using absolute positioning to center it you would want to change your left: 45%; to left: 50%; then set a transform like this:

.thing_to_center_horizontal {
    top 82px;
    left: 50%;
    transform: translateX(-50%);

This will make it center even with dynamic content.

left: 50%; will put it in the center based on the top left corner of the content, then transform: translateX(-50%); will move it 50% of the content's width (this is the dynamic part) to the left making it center.

Make sense?

But maybe a simple text-align: center; might work, but its hard to tell because you did not post any code.