文本换行时如何使宽度适合内容? [复制]
Posted
技术标签:
【中文标题】文本换行时如何使宽度适合内容? [复制]【英文标题】:How to make the width fit to the content when text wrapped? [duplicate] 【发布时间】:2022-01-06 21:36:09 【问题描述】:我正在使用顺风创建带有箭头的卡片。我希望箭头始终在文本 10px 旁边。但是当文字被换行时,文字的宽度大于文字的实际宽度。
我尝试添加width: fit-content
,但文本会溢出并且无法换行。如果我添加width: min-content
,那么文本总是换行。
在这种情况下,我必须使用 javascript 来获取文本的实际宽度,对吧?
这是我的代码:
<div class="grid grid-cols-3 gap-8 m-20 lg:max-w-[1200px]">
<div class="w-full h-52 overflow-hidden shadow-xl p-8 flex items-center justify-start gap-4">
<div class="min-w-[80px] min-h-[80px] bg-blue-500"></div>
<p class="text-xl font-bold">Software Solutions</p>
<svg viewBox="0 0 7 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.78125 0.75L6.25 5.5C6.375 5.65625 6.46875 5.84375 6.46875 6C6.46875 6.1875 6.375 6.375 6.25 6.53125L1.78125 11.2812C1.5 11.5938 1.03125 11.5938 0.71875 11.3125C0.40625 11.0312 0.40625 10.5625 0.6875 10.25L4.6875 6L0.6875 1.78125C0.40625 1.46875 0.40625 1 0.71875 0.71875C1.03125 0.4375 1.5 0.4375 1.78125 0.75Z" fill="#333940" />
</svg>
</div>
<div class="w-full h-52 overflow-hidden shadow-xl p-8 flex items-center justify-start gap-4">
<div class="min-w-[80px] min-h-[80px] bg-blue-500"></div>
<p class="text-xl font-bold pr-0 w-[fit-content]">Business process solutions</p>
<svg viewBox="0 0 7 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.78125 0.75L6.25 5.5C6.375 5.65625 6.46875 5.84375 6.46875 6C6.46875 6.1875 6.375 6.375 6.25 6.53125L1.78125 11.2812C1.5 11.5938 1.03125 11.5938 0.71875 11.3125C0.40625 11.0312 0.40625 10.5625 0.6875 10.25L4.6875 6L0.6875 1.78125C0.40625 1.46875 0.40625 1 0.71875 0.71875C1.03125 0.4375 1.5 0.4375 1.78125 0.75Z" fill="#333940" />
</svg>
</div>
</div>
【问题讨论】:
【参考方案1】:已编辑
我认为仅靠 CSS 是不可能的。
查看 JS 修复的答案:https://***.com/a/32222395/4536543
这是我的看法:
// get list of all spans
list = document.querySelectorAll('.content span');
for (var i=0; i<list.length; i++)
// retrieve width of span and apply it to parent
w = list[i].offsetWidth;
list[i].parentNode.style.width = w+1+"px"; // need to add 1 because sometimes width is not a whole number and Browser sometimes rounds it down which will trigger layout shift
<div style="background: green; width: 134px; position: relative">
<div class="content" style="background: yellow; float: left; max-width: 124px;">
<span style="background: grey">
somewhat long text goes here <!-- this is your "Business process solutions" -->
</span>
</div>
<div style="background: red; width: 10px; display: inline">
>
</div> <!-- this is your arrow -->
</div>
【讨论】:
谢谢,但正如我上面所描述的,min-content
使文本始终换行:这是我的代码:play.tailwindcss.com/ZgVEsnh4Hu
确实,我错过了。查看更新以上是关于文本换行时如何使宽度适合内容? [复制]的主要内容,如果未能解决你的问题,请参考以下文章