1

I would like to have a centered line next to my headline to the left and the right. I found a lot of solutions for a centered text, but not for a left aligned.

Is there a solution not using extra boxes and flex-grow?

The line should take the rest of the h2 element.

h2 {
  background-color: yellow;
}

h2:before {
  content: "";
  width: 2em;
  margin-right: 0.5em;
  display: inline-block;
  vertical-align: middle;
  border-bottom: 1px solid;
}

h2:after {
  content: "";
  /** How to calculate to 100% */
  width: 50%;
  margin-left: 0.5em;
  display: inline-block;
  vertical-align: middle;
  border-bottom: 1px solid;
}
<h2>Title</h2>

<h2>A long long Title</h2>
Matthias Baumgart
  • 905
  • 1
  • 9
  • 22
  • Possible duplicate of http://stackoverflow.com/questions/23584120/line-before-and-after-title-over-image/30736618#? (I'm referring to the accepted answer, you can adapt it to work with left aligned text.) – Harry Jan 06 '17 at 09:13

2 Answers2

4

Absolute position the pseudo elements:
https://jsfiddle.net/dhp6zrLp/

h2 {
  background-color: yellow;
  position: relative;
  overflow: hidden;
  padding-left: 2.5em;
}

h2:before {
  content: "";
  position: absolute;
  width: 2em;
  top: 51%;
  left: 0;
  display: inline-block;
  border-bottom: 1px solid;
}

h2:after {
  content: "";
  position: absolute;
  width: 100%;
  top: 51%;
  margin-left: 0.5em;
  display: inline-block;
  border-bottom: 1px solid;
}
<h2>Title</h2>

<h2>A long long Title</h2>
pol
  • 2,641
  • 10
  • 16
  • This is awesome, works nicely. Voted it up. But is there a way this can be made responsive if the text is much longer? – Gosi Jan 06 '17 at 09:41
0

You can always use image for that:

h2 {
  background: url('https://maxcdn.icons8.com/wp-content/uploads/2014/10/horizontal_line.png') center center yellow;
  text-align: center;
}
h2 span {
  background: yellow;
}
<h2><span>Title</span></h2>

<h2><span>A long long Title</span></h2>
Justinas
  • 41,402
  • 5
  • 66
  • 96