Search code examples
htmlcsscss-selectorspseudo-class

CSS - bottom border using :after pseudo-element that's the length of text


I have a <h3> that I need to style to contain a red bottom border behind it, using ::after pseudo element.

Goal: The red bottom border should only display the length of the text.

Result: The closest I have it right now, the border spans the parent width.

Border using CSS after pseudo

<h3><span class="headingLine">Lorem Ipsum Dolor Sit Amet</span></h3>

span.headingLine:after{
  position: absolute;
  content: '';
  border-bottom: 7px solid red;
  z-index: -1;
  left: 0;
  width: 100%; /* If I remove the width 100%, the red doesn't show */
  bottom: 15px;
  display: inline-block;
}

How do I adjust the markup / CSS so that the red border only spans the width of the text?

There may be instances of multiple lines of text (small browser window / lengthier heading)


Solution

  • Your approach is overcomplicated, just use a gradient background:

    h3 {
      border: solid 1px
    }
    
    span {
      background: linear-gradient(0deg, red 6px, transparent 7px) 0 1.1em
    }
    <h3><span class="headingLine">Lorem Ipsum Dolor Sit Amet</span></h3>
    <h3><span class="headingLine">Lorem Ipsum Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet</span></h3>