[英]Ajust div width to fit text after line-break
我想調整一個 div 寬度的大小,以使其始終適合里面的文本,即使有換行符也是如此。
有沒有辦法修改寬度以使其在使用 javascript 換行后適合文本?
body{ width: 600px; margin: 0px auto; } #container { border: 15px solid orange; display: flex; align-items: center; justify-content: space-between; } #firstDiv{ border: 10px solid brown; width: 130px; margin: auto 20px; } #secondDiv{ border: 10px solid skyblue; display: flex; align-items: center; margin: auto 20px; } #icon{ height: 24px; width: 24px; background-color: yellow; margin-right: 10px; } #thirdDiv{ border: 5px solid yellowgreen; width: 200px; margin: auto 20px; }
<div id="container"> <div id="firstDiv">FIRST</div> <div id="secondDiv"> <span id="icon"></span> <span id="legend">I want the #secondDiv width to fit this text</span> </div> <div id="thirdDiv">THIRD</div> </div>
編輯:
問題是因為#secondDiv
末尾有一些空白,# #firstDiv
和#secondDiv
之間的空間看起來與#secondDiv
和#thirDiv
之間沒有邊界時的空間不同。
如果您指示該元素使用所有剩余空間 ( width:100%
),則文本將盡可能填充所有空間。
body{ width: 600px; margin: 0px auto; } #container { border: 15px solid orange; display: flex; align-items: center; justify-content: space-between; } #firstDiv{ border: 10px solid brown; width: 130px; margin: auto 20px; } #secondDiv{ border: 10px solid skyblue; display: flex; align-items: center; margin: auto 20px; width:100%; /* Instruct element to take 100% of the remaining space */ } #icon{ height: 24px; width: 24px; background-color: yellow; margin-right: 10px; } #thirdDiv{ border: 5px solid yellowgreen; width: 200px; margin: auto 20px; }
<div id="container"> <div id="firstDiv">FIRST</div> <div id="secondDiv"> <span id="icon"></span> <span id="legend">I want the #secondDiv width to fit this text</span> </div> <div id="thirdDiv">THIRD</div> </div>
我剛剛更改了一些 css 代碼,使這三個 div inline
並刪除了display:flex
body{ width: 600px; margin: 0px auto; } #container { border: 15px solid orange; text-align: center; justify-content: space-between; } #firstDiv{ border: 10px solid brown; width: 130px; margin: auto 5px; display:inline-block; } #secondDiv{ border: 10px solid skyblue; text-align: center; margin: auto 5px; width:auto; display:inline-block; } #icon{ height: 24px; width: 24px; background-color: yellow; margin-right: 10px; } #thirdDiv{ border: 5px solid yellowgreen; margin: auto 5px; display:inline-block; width:auto; text-align: center; }
<div id="container"> <div id="firstDiv">FIRST</div> <div id="secondDiv"> <span id="icon"></span> <span id="legend">I want the #secondDiv width to fit this text</span> </div> <div id="thirdDiv">THIRD</div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.