MSC
MSC

Reputation: 3386

Centred, underlined headings where the underline is a different colour from the text

What's the most straightforward way to style HTML headings such that they are both underlined and horizontally centered? I don't want the underline to extend to the full width of the container, just the words. I also want the underline to be a different colour from the text and some distance away.

At the moment I am using a span inside the h2 to achieve this (in Sass):

    h2 {
        text-align: center;
        span {
            border-bottom: 2px solid #e6ebdf;
        }
    }

Is there a way to do so without an inner span or adding styles to the parent container? Here's the result. Note how the underline is (a) a different colour from the text and, (b) not tight against the bottom of the text the way it would be using text-decoration: underline:

enter image description here

Upvotes: 1

Views: 1148

Answers (2)

Temani Afif
Temani Afif

Reputation: 274097

Another idea is to use table to center and then apply a gradient where you can easily adjust the size, position and color:

h2 {
  display:table;
  text-align:center;
  margin:auto;
  padding-bottom:5px; /*control the distance*/
  background:
    linear-gradient(red,red) bottom /80%   2px   no-repeat;
    /*                     position /width height   */
}
<h2>Hello</h2>

Upvotes: 3

Web Nexus
Web Nexus

Reputation: 1158

You can do this with the following:-

h2 {
  text-decoration: underline;
  text-align: center;
  text-decoration-color: red;
  text-underline-position: under;
}
<h2>Hello</h2>

Browser support maybe limited though, you may need to check.

Upvotes: 2

Related Questions