3

I am trying to create a heading with a nice underline. Not an actual CSS underline, but an underline partly overlaps my headings.

My code works correct for single line headings, but I am using this for a CMS, so it is possible that the headings become longer (multi-line). This is where I run into problems.

I understand that this is because the line gets inserted ::after the content, but I don't know if there is anything available to do it per line.

Code example

The code below shows two headings. As you can see, the correct underline works for one line only. Is there a solution on how to get the underline for multi-lines instead of sticking it under the complete block?

h1{
    font-weight: 600;
    margin: 0 0 5px 0;
    position: relative;
    display: inline;
}

h1::after{
    content: '';
    position: absolute;
    display: block;
    width: 100%;

    z-index: -1;

    opacity: 60%;
    bottom: 0.1em;
    height: 0.25em;
    background-color: lightblue;
}
<h1>Just a heading</h1>
<br>
<br>
<h1>A very very very very very very very very very very very very very very very very very very very very example long heading</h1>
Timmofo
  • 33
  • 4
  • Are you able to use a span as suggested in https://stackoverflow.com/questions/38696914/how-to-underline-whole-heading-divided-into-two-lines? – cprlkleg Sep 01 '20 at 10:59
  • Nope, I tried it, but my headings are all block line elements. It's not possible to add spans in due to the size of the project. I do appreciate the feedback! – Timmofo Sep 01 '20 at 11:12

2 Answers2

3

You can use inverted box-shadow instead.

Like so -

h1{
    font-weight: 600;
    margin: 0 0 5px 0;
    position: relative;
    display: inline;
    box-shadow: inset 0 -3px #fff, inset 0 -12px lightblue;
}
<h1>Just a heading</h1>
<br>
<br>
<h1>A very very very very very very very very very very very very very very very very very very very very example long heading</h1>
Debsmita Paul
  • 1,442
  • 9
  • 22
  • 1
    Thank you, this is exactly what I was looking for! Working with inverted/ negative values always throws me off. – Timmofo Sep 01 '20 at 11:13
2

You can do something like this :

h1{
    font-weight: 600;
    margin: 0 0 5px 0;
    position: relative;
    display: inline;
    text-decoration: underline lightblue;
}
<h1>Just a heading</h1>
<br>
<br>
<h1>A very very very very very very very very very very very very very very very very very very very very example long heading</h1>
Pranav Rustagi
  • 2,604
  • 1
  • 5
  • 18
  • 2
    Thank you very much for your reply. It was not what I was exactly looking for, because this doesn't have the same styling as my initial design. But I appreciate the effort and will update my question to make it more clear. – Timmofo Sep 01 '20 at 11:09