Restrict border width to text width in a block element

Vince picture Vince · May 6, 2013 · Viewed 63.6k times · Source

I have an <h2> title into a fixed with <div> (238px). When this page is rendered, the browser manage line breaks into the title to make the text fit the width (238px).

But the width property of the h2 element is still 238px, no matters where the line breaks are.

I want to set a border-bottom only under the text, and not under the full width of the h2 element, and I don't know how to achieve this using CSS.

You can see what I mean here : http://jsfiddle.net/np3rJ/2/

Thanks

Answer

Laurent S. picture Laurent S. · May 6, 2013

I think this is what you need:

<h2><span>Horizon 2020, nouvelles opportunités</span></h2>
h2 span {
    position: relative;
    padding-bottom: 5px;
}
h2 span::after{
    position: absolute; 
    left: 0; 
    bottom: 0; 
    width: 100%; 
    height: 1px; 
    border-bottom: 1px solid #000; 
    content: ""
}

Working demo in jsFiddle

I used the technique described in this answer: Advanced CSS challenge: underline only the final line of text with CSS

I introduced a span into the H2 in order not to change the display attribute of it, but you could just as easily use the same technique with a display: inline on your H2. This method would allow the control of the actual line though rather than setting display: inline if needed