【问题标题】:Lined title in CSS/HTML [duplicate]CSS / HTML中的内衬标题[重复]
【发布时间】:2019-09-06 23:46:51
【问题描述】:

我正在尝试使用 flexbox 制作一个内衬标题。它可以工作,但标题中的文本转到下一行,这不是我想要的 - 它应该全部保留在一行中。

.hr {
  width: 100%;
  display: flex;
  align-items: center;
}

.line {
  height: 3px;
  background: red;
  display: inline-block;
  width: 100%;
}
<div class='hr'>
  <div class='title'>
    Apes are cool animals
  </div>
  <div class='line'></div>
</div>

<div class='hr'>
  <div class='title'>
    Aren't they?
  </div>
  <div class='line'></div>
</div>

JSFiddle

预期结果: https://i.gyazo.com/3164ae24d7fd2402fa711126d04319b1.png

【问题讨论】:

  • 注意inline-block没用可以去掉

标签: html css flexbox


【解决方案1】:

添加一条规则以阻止文本用.title { white-space: nowrap; } 换行:

.hr {
  width: 100%;
  display: flex;
  align-items: center;
}

.line {
  height: 3px;
  background: red;
  display: inline-block;
  width: 100%;
}

.title {
  white-space: nowrap;
}
<div class='hr'>
  <div class='title'>
    Apes are cool animals
  </div>
  <div class='line'></div>
</div>

<div class='hr'>
  <div class='title'>
    Aren't they?
  </div>
  <div class='line'></div>
</div>

【讨论】:

    【解决方案2】:

    一种方法是在.line 中使用flex: 1 而不是width: 100%。这使得该行尽可能长以覆盖标题留下的空间。

    示例:

    .hr {
      width: 100%;
      display: flex;
      align-items: center;
    }
    
    .line {
      height: 3px;
      background: red;
      display: inline-block;
      flex: 1;
    }
    <div class='hr'>
      <div class='title'>
        Apes are cool animals
      </div>
      <div class='line'></div>
    </div>
    
    <div class='hr'>
      <div class='title'>
        Aren't they?
      </div>
      <div class='line'></div>
    </div>

    【讨论】:

      【解决方案3】:

      您可以将flex-shrink: 0 添加到title默认flex-shrink: 1 用于弹性项目 - 请参见下面的演示:

      .hr {
        width: 100%;
        display: flex;
        align-items: center;
      }
      
      .line {
        height: 3px;
        background: red;
        display: inline-block;
        width: 100%;
      }
      
      .title {
        flex-shrink: 0; /* added */
      }
      <div class='hr'>
        <div class='title'>
          Apes are cool animals
        </div>
        <div class='line'></div>
      </div>
      
      <div class='hr'>
        <div class='title'>
          Aren't they?
        </div>
        <div class='line'></div>
      </div>

      【讨论】:

        猜你喜欢
        • 2018-11-12
        • 1970-01-01
        • 2014-08-30
        • 2023-02-13
        • 1970-01-01
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多