Create line after text with css

You could achieve this with an extra <span>:

h2 {
  font-size: 1rem;
  position: relative;
}

h2 span {
  background-color: white;
  padding-right: 10px;
}

h2:after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 0.5em;
  border-top: 1px solid black;
  z-index: -1;
}
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>

Another solution without the extra <span> but requires an overflow: hidden on the <h2>:

h2 {
  font-size: 1rem;
  overflow: hidden;
}

h2:after {
  content: "";
  display: inline-block;
  height: 0.5em;
  vertical-align: bottom;
  width: 100%;
  margin-right: -100%;
  margin-left: 10px;
  border-top: 1px solid black;
}
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>

External examples: First, Second


There's no need for extra wrappers or span elements anymore. Flexbox and Grid can handle this easily.

h2 {
  display: flex;
  align-items: center;
}

h2::after {
  content: '';
  flex: 1;
  margin-left: 1rem;
  height: 1px;
  background-color: #000;
}
<h2>Heading</h2>

Tags:

Css