5

I am currently trying to make a custom underline with border-bottom. However, currently the underline is going all the way of my block-element (whole page).

I’d prefer to have it being only 50px longer than my headline (however the text is flexible and I do not know the length).

Can I do this without adding another <span> tag within the <h2> somehow? I do not wannt to add a <span> element to each <h2> just to change my design.

Current HTML is:

<h1>My title</h1>

CSS:

h1 {
    font-size: 18px;
    color: #b62525;
    border-bottom: 2px solid #c68181;
}

Is it possible to adjust the border-bottom length to my text length? (e.g. behave like inline element for border, but like block for newlines, padding and margin)

aufziehvogel
  • 7,167
  • 5
  • 34
  • 56

4 Answers4

4

Using display: inline-block works, the only caveat being that the content after the <h1> tag must be the full width of the container element. The other solutions here also assume this. You can also use display: inline (supported by older browsers), but inline-block allows for setting of explicit widths, should you need it.

Here's a JSFiddle

CSS

h1
{
    display: inline-block;
    padding-right: 50px;
    border-bottom: 1px dotted #888;
}
Community
  • 1
  • 1
Bojangles
  • 99,427
  • 50
  • 170
  • 208
3

Inline or floating methods can be problematic if you're unable to compensate for them in other rules. One alternative is to use display:table

h1
{
        display:table;
        border-bottom:1px solid black;
        padding-right:50px;
}
Community
  • 1
  • 1
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
  • Is it good style to set display: table on a block element? As for web designers came to the conclusion, that it’s only for tabular content and not for design. What about display: table?
    – aufziehvogel Sep 03 '11 at 16:48
  • 1
    Just to note, `display: table` isn't supported by [IE7 and below](http://www.quirksmode.org/css/display.html). – Bojangles Sep 03 '11 at 21:20
2

You can use

  h1 {
        font-size: 18px;
        color: #b62525;
        border-bottom: 2px solid #c68181;
        float: left;
        padding-right: 50px
     }
Ivan Nikolchov
  • 1,574
  • 1
  • 27
  • 41
1

Simply add one more property in css like this :

h1 {
    display:inline;
    font-size: 18px;
    color: #b62525;
    border-bottom: 2px solid #c68181;
}
Tushar Ahirrao
  • 12,669
  • 17
  • 64
  • 96