Nazareno Lorenzo
Nazareno Lorenzo

Reputation: 1079

How to code a centered short underline?

example

I have to mockup this, and I though about 2 ways to do it:

  1. Background image with the line
  2. Adding another element of 1px height, with a green top/bottom border. I could even do this using the :after selector

But I'm not convinced by any of the two. The first one because it needs an extra image, and the second one because it implies adding an extra element, which won't be semantically correct.

Is there any way without adding elements or images?

Upvotes: 1

Views: 593

Answers (1)

Donnie D'Amato
Donnie D'Amato

Reputation: 3940

I love pseudo elements so that's exactly what I would use here.

h1{
   position:relative;
}

h1:after{
   content:"";
   position:absolute;
   width:20%;
   border-top:1px solid green;
   bottom:0;
   left:40%;
}

If you want the underline to be a fixed width, you'll need to use negative margins to center it.

h1:after{
   content:"";
   position:absolute;
   width:100px;
   border-top:1px solid green;
   bottom:0;
   left:50%;
   margin-left:-50px;
}

Upvotes: 9

Related Questions