我有一个像这样的 h4 元素:
<h4 class="hero-title">
<span>Vessel / tank destruction facility</span>
</h4>
CSS 是这样的:
.hero-title {
background: #000;
color: #ffffff;
display: inline-block;
padding: 20px;
max-width: 473px;
}
结果如下:
我想删除右侧多余的间距。这样黑色背景应该以“Vessel / Tank”结束,换句话说,当发生换行时,与最宽的单词对齐,而不是占据整个 473px 宽度。
我找不到任何 CSS 方法来执行此操作。我只使用 JavaScript 找到了这个解决方案。
基本上,我们计算文本的边界框,然后根据该边界框确定父级的宽度。 (只需确保
box-sizing
设置为 border-box
。):
function adjustContainerWidth(element) {
const textSpan = element.getElementsByTagName('span')[0];
const boundingRect = textSpan.getBoundingClientRect();
const horizontalPadding = parseInt(getComputedStyle(element).paddingLeft) + parseInt(getComputedStyle(element).paddingRight);
element.style.width = (boundingRect.width + horizontalPadding) + 'px';
}
const elements = Array.from(document.getElementsByClassName('hero-title'));
elements.forEach((element) => {
adjustContainerWidth(element);
});
.hero-title {
background: #000;
color: #ffffff;
display: inline-block;
padding: 20px;
max-width: 473px;
box-sizing: border-box; /* for correct width calculation */
font-size: 60px;
margin: 5px;
}
<h4 class="hero-title">
<span>Vessel / tank destruction facility</span>
</h4>