我有一个仅包含文本句子的元素,例如:
<p>Click here to see the Product Widget Name in action</p>
元素中的文本将根据其显示的产品页面而变化。
该元素的高度为45px,但宽度可变。我想要做的就是使宽度尽可能小,而不会使文本溢出元素。所以我希望文本在元素的 45px 高度内尽可能多地换行,因此宽度尽可能小。
但是我似乎无法让它在 CSS 中以任何方式工作。以下是我尝试过的一些内容,如果需要,可以添加更多元素来完成这项工作。
p {
height: 45px;
font-size: 8pt;
line-height: 1.15;
border:1px solid black;
width:1px;
max-width:fit-content;
min-width:min-content;
}
<p>Click here to see the Product Widget Name in action</p>
p {
height: 45px;
font-size: 8pt;
line-height: 1.15;
border:1px solid black;
width:min-content;
max-width:fit-content;
min-width:min-content;
}
<p>Click here to see the Product Widget Name in action</p>
p {
height: 45px;
font-size: 8pt;
line-height: 1.15;
border:1px solid black;
width:auto;
max-width:min-content;
min-width:fit-content;
}
<p>Click here to see the Product Widget Name in action</p>
我知道我可以在 JS 中做到这一点,但如果可以的话我宁愿避免它。如果 JS 是唯一的方法,我是否必须通过循环多个宽度来使用试错方法,直到达到正确的平衡?
如果有解决办法请告诉我!
如果我正确理解了您的问题,除了根据元素的宽度和高度更改文本的字体之外,您没有其他方法。通过这种方式,您将拥有固定的宽度和高度大小,并且只有通过更改字体大小,您的文本才能适合元素。现在,如果这就是您正在寻找的,那么这里是找到最适合您的最佳解决方案的完美来源。 基于容器宽度的字体缩放
我希望这可以帮助你
p {
width: 50px;
border: 2px solid black;
padding: 10px;
word-wrap: break-word;
font-size: 20px;
}
<p> In this paragraph, there is a very long word:
iamsooooooooooooooooooooooooooooooolongggggggggggggggg. The long word will break and wrap to the next line. </p>
如果想要最大高度并使其看起来“漂亮”,可以添加
text-overflow: ellipsis;
来隐藏叠加层
p {
text-overflow: ellipsis;
height: 45px;
width: 150px;
border: 2px solid black;
padding: 10px;
word-wrap: break-word;
overflow: hidden;
white-space: nowrap;
font-size: 20px;
}
<p title="some info that user can see on hover is text is not readable"> In this paragraph, there is a very long word:
iamsooooooooooooooooooooooooooooooolongggggggggggggggg. The long word will break and wrap to the next line. </p>