aufziehvogel
aufziehvogel

Reputation: 7297

How can I make an underline some pixels longer than the headline?

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)

Upvotes: 6

Views: 21424

Answers (4)

Paul Dixon
Paul Dixon

Reputation: 300825

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;
}

Upvotes: 3

Bojangles
Bojangles

Reputation: 101473

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;
}

Upvotes: 4

Tushar Ahirrao
Tushar Ahirrao

Reputation: 13115

Simply add one more property in css like this :

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

Upvotes: 1

Ivan Nikolchov
Ivan Nikolchov

Reputation: 1574

You can use

  h1 {
        font-size: 18px;
        color: #b62525;
        border-bottom: 2px solid #c68181;
        float: left;
        padding-right: 50px
     }

Upvotes: 2

Related Questions