搜尋

首頁  >  問答  >  主體

使用flexbox來根據內容的寬度創建span的方法

<p>我已經在寬度固定的flex-row父元素中使用了span和div</p> <p><br /></p> <pre class="brush:css;toolbar:false;">.parent { display: flex; flex-direction: row; width: 230px; background-color: blue; } .child1 { background-color: red; } .child2 { min-width: 40px; }</pre> <pre class="brush:html;toolbar:false;"><div class="parent"> <span class="child1">這是span中的一些文字</span> <div class="child2"/> </div></pre> <p><br /></p> <p>我希望span永遠與文字的寬度相同,而div則佔據父元素剩餘的整個寬度。現在(如您在程式碼片段中所見),當文字移到新行時,紅色背景區域的寬度比文字寬。如何修復這段程式碼?我需要紅色背景正好結束在文字的邊緣</p>
P粉726234648P粉726234648590 天前556

全部回覆(1)我來回復

  • P粉147747637

    P粉1477476372023-08-16 00:16:31

    也許你可以將parent設定為網格並使用fr單位進行測量?

    grid-template-columns: fit-content, 1fr

    這將使文字容器的寬度與文字的確切寬度相同,並使剩餘的容器佔據剩餘空間的1份(沒有其他容器會佔據100%的空間)。

    對於行顯示,只需將columns更改為rows。

    回覆
    0
  • 取消回覆