I have a <h4>
element like this:
<h4 class="hero-title">
<span>Vessel / tank destruction facility</span>
</h4>
And css like this:
.hero-title {
background: #000;
color: #ffffff;
display: inline-block;
padding: 20px;
max-width: 473px;
}
Here is the outcome:
I want to remove the extra spacing on the right side, so that the black background ends at "Vessel / tank", in other words, when line break happens, it should align with the widest word and not take up the entire 473px width.
2
Answers
I couldn’t find any CSS method to do this. I only found this solution using JavaScript.
Basically, we calculate the bounding box of the text and then determine the width of the parent based on that. (Just make sure that
box-sizing
is set toborder-box
.):You can use this solution only with CSS.