0

I wanted to add a thicker underline to my h1 tags so I used "border-bottom" as suggested in multiple Stack Overflow questions. However, the border extended well beyond the text, so I decided to add the display property "inline-block" to make the border conform to the text's bounds. This, however, made the element lack a line break after the content. I know I could always add the "br" tag, but I'd prefer to keep that in my styling. Is there anything I can do? Here is my current CSS:

h1
{
    font-weight:normal;
    margin-bottom:5px;
    border-bottom: 2px solid;
    display: inline-block;
}
Jack Guy
  • 8,346
  • 8
  • 55
  • 86
  • Just wrap the H1 tag in a block element, like a DIV. Or put the content that follows it in a block element... – nice ass Feb 25 '13 at 00:50
  • Have a look at the CSS box model (http://www.w3.org/TR/CSS2/box.html). Generally if you remove all of the padding and increase the margins, the border will match the text much better. I know that this doesn't quite answer the question, but is a different solution. – Marryat Feb 25 '13 at 00:54

3 Answers3

7

Try display: table instead. It acts similar to inline-block in that it collapses down to to the width of its children, but prevents surrounding inline elements from flowing along side of it the same way an ordinary block element does.

http://codepen.io/cimmanon/pen/FvGxl

cimmanon
  • 67,211
  • 17
  • 165
  • 171
3

If the width of your <h1> text is fixed, you can set the width and keep it display: block;.

Demo: jsFiddle

Output:

enter image description here

CSS:

h1 {
    border-bottom: 2px solid black;
    font-weight:normal;
    margin-bottom:5px;
    width: 140px;
}

HTML:

<h1>underlined</h1>
next line
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
1

Since you don't always want border-bottom (eg, navigation item with padding), this method works better:

h1:after {
    content: '';
    height: 1px;
    background: black; 
    display:block;
}

If you want more or less space between the text and the underline, add a margin-top.

If you want a thicker underline, add more height:

h1:after {
    content: '';
    height: 2px;
    background: black; 
    display:block;
    margin-top: 2px;
}
jake
  • 830
  • 9
  • 10