Reputation: 3773
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?
html:
<div id="countup-container">
<img id="countup-image" src="https://i.sstatic.net/9YqKE.png" alt="Accident Free Days">
<span id="ctl00" class="countup-text">101</span>
</div>
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;
}
Upvotes: 0
Views: 1689
Reputation: 3456
If I understand you, you could simply add text-align:center
to your #countup-container
.
And remove left:45%
to your .countup-text
Upvotes: 0
Reputation: 12581
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.
Upvotes: 3