Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict border width to text width in a block element

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

like image 891
Vince Avatar asked May 06 '13 12:05

Vince


People also ask

How do you control border bottom width?

The border-bottom-width property sets the width of an element's bottom border. Note: Always declare the border-style or the border-bottom-style property before the border-bottom-width property. An element must have borders before you can change the width.


1 Answers

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

like image 161
Laurent S. Avatar answered Sep 29 '22 07:09

Laurent S.