CSS / HTML中的行标题

时间:2019-04-16 19:40:26

标签: html css css3 flexbox

我正在尝试使用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

3 个答案:

答案 0 :(得分:2)

添加一条规则以阻止文本以.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>

答案 1 :(得分:2)

执行此操作的一种方法是使用flex: 1而不是width: 100%中的.line。这样可以使行尽可能长以覆盖标题剩余的空间。

示例:

.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>

答案 2 :(得分:1)

您可以将flex-shrink: 0添加到title中( flex项的默认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>