我想要一个<p>
元素内有 1-3 个单词,因此每个新单词将占一个新行。理想情况下,我想做 <p>
元素与最长单词一样宽。我无法插入<br>
或其他html
,因为数据来自第三方 API。
目前我发现的唯一方法是修复 <p>
长度,但对于长单词,结果相当难看。
有 CSS 替代方案吗?干杯!
p {
max-width: 48px;
background-color: blue;
color: white;
padding: 8px 16px;
border-radius: 4px;
word-break: break-all
}
<p>extra super tag</p>
<p>extra tagverylong tag</p>
最佳答案
使用宽度:最小内容
p {
width: min-content;
background-color: blue;
color: white;
padding: 8px 16px;
border-radius: 4px;
}
<p>extra super tag</p>
<p>extra tagverylong tag</p>
使用 inline-block
获得更好支持的另一个技巧
p {
display:inline-block;
background-color: blue;
color: white;
padding: 8px 16px;
border-radius: 4px;
}
.main {
width:0;
}
<div class="main">
<p>extra super tag</p>
<p>extra tagverylong tag</p>
</div>
还有表格
:
p {
display: table;
width: 1px;
background-color: blue;
color: white;
padding: 8px 16px;
border-radius: 4px;
}
<p>extra super tag</p>
<p>extra tagverylong tag</p>
关于html - <p> block 在每个单词后换行,宽度限制为最长单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65373603/