CSS How to match text width with width of dynamically sized image/header
CSS How to Match Text Width to the Width of Dynamically Resized Images/Titles
In this article, we’ll show you how to use CSS to match text width to the width of dynamically resized https://coder-cafe.com/wp-content/uploads/2025/09/images or titles.
Read more: CSS Tutorial
Using Flexbox Layout
In CSS, we can use flexbox layout to easily match the width of text to the width of https://coder-cafe.com/wp-content/uploads/2025/09/images/titles. We can achieve this by placing the text in a flex container and making the image/title a flex item.
First, we need to create a container. We can use the <div>
element and add a class name to it.
<div class="container">
<div class="image">
<!-- Image -->
</div>
<div class="text">
<!-- Text -->
</div>
</div>
Next, we need to add some CSS styles to the container to define the flexbox layout.
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
The above code sets our container as a flex container, creates a horizontal gap between the image/title and the text, and aligns them vertically.
Then, we need to add the appropriate CSS styles to the image and text to make them flex items.
.image {
flex: 1;
}
.text {
flex: 2;
}
The above code sets the image’s flex property to 1 and the text’s flex property to 2, making the text twice as wide as the image.
Using the calc() Function
In addition to using flexbox layouts, you can also use the calc() function to calculate the width of text. The calc() function allows us to perform basic mathematical operations such as addition, subtraction, multiplication, and division.
We can set the width of the text to be equal to the width of the image by using the calc() function. Here’s an example:
.text {
width: calc(100% - 200px);
}
In the above code, we use the calc() function to calculate the width of the text. The text width will be 100% minus the image width (assuming the image width is 200px).
Dynamic Width Calculation with JavaScript
If the image or title size changes dynamically, we can use JavaScript to dynamically calculate the text width and set its width accordingly.
First, we need to add an event listener to the image or title element to trigger the function that calculates the text width when its size changes.
const image = document.querySelector('.image');
const text = document.querySelector('.text');
image.addEventListener('load', calculateTextWidth);
image.addEventListener('resize', calculateTextWidth);
In the above code, we use the querySelector() method to select the image and text elements, and use the addEventListener() method to bind the load and resize events to the function that calculates the text width.
Next, we need to write a function to calculate the text width.