1

I'm trying to make a lined title with flexbox. It works but the text in the title goes to the next line, which is not what I want - it should all stay in one line.

.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

Expected Result: https://i.gyazo.com/3164ae24d7fd2402fa711126d04319b1.png

kukkuz
  • 41,512
  • 6
  • 59
  • 95
Martijn Ebbens
  • 514
  • 2
  • 5
  • 14

3 Answers3

2

Add a rule to stop the text from wrapping with .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>
j08691
  • 204,283
  • 31
  • 260
  • 272
2

One way of doing this is by using flex: 1 instead of width: 100% in .line. This makes the line as long as it needs to be in order to cover the space left by the title.

Example:

.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>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
1

You can add flex-shrink: 0 to the title (the default is flex-shrink: 1 for a flex item - see demo below:

.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>
kukkuz
  • 41,512
  • 6
  • 59
  • 95