Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - 换行后调整div宽度以适合文本(Ajust div width to fit text after line-break)

I would like to resize a div width to make it always fit the text inside even when there is a line-break.

(我想调整div宽度的大小,以使其始终适合内部文本,即使有换行符也是如此。)

Is there a way to modify the width to make it fit the text after a line break using javascript?

(有没有办法使用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> 

Edits:

(编辑:)

The problem is because there is some blank space at the end of the #secondDiv the space between #firstDiv and #secondDiv appears not the same than between #secondDiv and #thirDiv when there is no borders.

(问题是因为#secondDiv的末尾有一些空白,当没有边界时, #secondDiv#thirDiv之间的空间#firstDiv#secondDiv#secondDiv之间的空间不同。)

  ask by Below the Radar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you instruct that element to use all of the remaining space ( width:100% ) the text will fill whatever space it can.

(如果您指示该元素使用所有剩余空间( 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> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...