22

Is it possible with CSS to make the underline of a headline less wide than the headline text? I have the following style for an H1 headline:

h1 {
  font-weight: 300;
  display: inline-block;
  padding-bottom: 5px;
  border-bottom: 1px #d2202f solid;
}

This produces a thin red underline below my H1 headlines. However, is it possible to make it so that the underline is 50% of the text in the headline?

therealbiglou
  • 263
  • 1
  • 3
  • 15

2 Answers2

63

You can use a pseudo element with :before (or :after):

h1 {
    font-weight: 300;
    display: inline-block;
    padding-bottom: 5px;
    position: relative;
}
h1:before{
    content: "";
    position: absolute;
    width: 50%;
    height: 1px;
    bottom: 0;
    left: 25%;
    border-bottom: 1px solid red;
}

http://jsfiddle.net/9e27b/

James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • 2
    Not working with multiple lines of text... – Meek Jan 02 '17 at 11:36
  • 1
    For multiline: content: ''; bottom: 0; left: 30%; right: 30%; height: 2px; background: red; display: block; width: 50%; position: static; margin-left: 25%; – TheKitMurkit Jun 08 '18 at 12:45
3

Yes and no.

Normal borders cannot do this, but you can fake it with a CSS3 gradient border.

See: CSS3 Gradient Borders

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • 9
    Please improve the answer quality a little bit, maybe with some example. I cannot vote for deletion as it is not bad enough, but it is not good enough aswell. – Alexey Malev May 22 '14 at 11:54