I am trying to create a div that contains an img and a text over the img. The text will be with different size depending on the case, so I want to automatically adjust the width of the img to cover the text.
What I tried so far is this:
/* Container holding the image and the text */
.cartContainer {
width: max-content;
position: relative;
text-align: center;
display: inline-block;
margin: 0;
}
/* Centered text */
.cartTextCentered {
position: absolute;
display: block;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: fit-content;
}
.cartImg {
max-height: 1.5rem;
display: block;
transform: translate(0, 0.1em);
width: fit-content;
}
<div class="cartContainer">
<img class="cartImg" src="imagePath">
<div class="cartTextCentered">
This is my text.
</div>
</div>
I would greatly appreciate anyhelp on the topic.
Revised:
This is what I want to achieve:
enter image description here
And this is if I use background-image:
enter image description here
2
Answers
You can achieve dynamic font sizing based on container width using vw units (viewport width) or other relative units in combination with media queries or CSS calculations.
you can turn cartContainer into Flex container with
flex-direction
set to column and define it’s block size, after you can give each childflex:1;
which will cause each of them to shrink and grow equally and take up same amount of space vertically. Besides instead of using width and height I have replaced them with more robust inline-size and block-size properties. Hope this solves your problem.