换行后调整div宽度以适合文本

时间:2019-11-29 18:43:02

标签: javascript css

我想调整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和{{ 1}}没有边界。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我刚刚更改了一些CSS代码,使这三个div成为<select @bind="MyLocalParameter"> <option value="">All</option> @foreach (var item in Items) { <option value="@item.IdGuid">@item.Name</option> } </select> ,并删除了if month == 12, season = 'Winter' elif month == 2, season = 'Spring' elif month == 5, season = 'Summer' else month == 8, season = 'Fall'

inline
display:flex