t3ol5
t3ol5

Reputation: 94

Breakable colored underline in CSS

I would like to have a colored underline that looks like this when it breaks:
Heading with colored underline in one and two lines

text-decoration-color seems to be not supported widely enough.

I tried this:

.underline {
  position: relative;
 }

.underline:after {
  position: absolute;
  content: '';
  height: 1px;
  background-color: #ffc04d;
  bottom: .1rem;
  right: 0;
  left: 0;
  z-index: -1;
}
 <h1><span class="underline">Sprouted Bread</span></h1>

and this is what it looks like when it breaks.

Upvotes: 5

Views: 410

Answers (3)

Temani Afif
Temani Afif

Reputation: 272937

What about a linear-gradient where it will be easy to control color, size and distance within a single element:

.underline {
  position: relative;
  font-size:28px;
  background:
    linear-gradient(yellow,yellow) /* Color */
    left 0 bottom 2px/ /* Position */
    100% 2px  /* Size (width height)*/
    no-repeat;
 }
<div style="width:150px;text-align:center"><span class="underline">Sprouted Bread</span></div>

As a side note, border-bottom works fine used with inline element but of course you cannot easily control the distance to make it behave as a text-decoration:

.underline {
  position: relative;
  font-size:28px;
  border-bottom:2px solid yellow;
 }
<div style="width:150px;text-align:center"><span class="underline">Sprouted Bread</span></div>

Upvotes: 4

Chris Happy
Chris Happy

Reputation: 7295

Just add a border!

Using display: inline, add a bottom border and space it with padding.

You could also use line-height and then place negative margins to increase the space in between the lines.

And...you could also animate it!

.underline {
  position: relative;
  padding-bottom: 1px;
  border-bottom: 1px solid #ffc04d;
}
<h1 style="width: 5em">
  <span class="underline">Sprouted Bread</span>
</h1>

As mentioned by @chriskirknielsen, you could use box-decoration-break, although not supported by IE or Edge. Credits: @Temani Afif

Upvotes: 1

Jay
Jay

Reputation: 1678

Try this JSFiddle

By wrapping the elements like you have in a span. You can put the text decoration on the parent element and the text color on the span.

HTML:

<h1><span class="underline">Some Text</span></h1>

CSS:

h1 {
  text-decoration: underline;
  color: red;
}

.underline {
  color: blue;
}

Upvotes: 3

Related Questions