文本换行时如何使宽度适合内容?

dun*_*act 9 html css tailwind-css

我正在使用顺风创建一张带有箭头的卡片。我希望箭头始终位于文本旁边 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 width="7" height="12" 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 width="7" height="12" 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>
Run Code Online (Sandbox Code Playgroud)

Max*_*rok 2

已编辑

我认为仅靠 CSS 是不可能实现这一点的。

请参阅此答案以获取 JS 修复:/sf/answers/2255567681/

这是我的看法:

// 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
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)