update
You can now use text-decoration: underline
and various new related properties to adjust thickness, colour and distance to get the underline exactly how you wish.
text-decoration-color: #fff;
text-decoration-thickness: from-font; /* or numerical value, eg 0.2ex */
text-decoration-style: wavy;
text-decoration-skip: edges;
text-underline-offset: 4px;
text-underline-position: under; /* could be left, right, auto or even under left */
Original article
So I had a problem adding a bottom border to the h2 elements that only ran the width of the word.
Normally I just set this to display: inline-block
. However if an h2 heading was short enough and came immediately after a pre
block the h2 wouldn’t start a new line.
I found a fix on Stack Overflow.
I had to use display: table-cell
on the h2
s.
h2 {
display: table-cell;
}
Then create a pseudo-element also set to table-cell
AND with a width of 100%. The 100% means it takes up the rest of all the available space.
h2::after {
display: table-cell;
width: 100%;
}
Finally a problem with the fact that the table-cell
value seems to collapse the margins meant I couldn’t set margins on the h2. Instead I added a margin-top
to every element after the h2:
h2 + * {
margin-top: 0.5em;
}
Finally I had the problem the the h2’s also had no top margin either. Another pseudo-element was all that was needed:
.old h2::before {
content: ' ';
display: block;
margin-top: 1em;
}
Conclusion
Whether this is still the best way to do this I don’t know. There’s so much CSS now. Maybe using min-content
might work. Another I came across involved using the break character as the content of the pseudo-element:
h2::before {
content: '\A';
white-space: pre;
}
…though this didn’t work for me.
I’m satisfied. I fixed the problem with only the CSS so it is fixed globally.