Restrict border width to text width in a block element

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


Maybe display: inline-block; Or display: inline; is what you need?


If you are willing to use display: table-cell, and pseudo-elements, you can have a pretty good solution (with some minor limitations).

The HTML does not change:

<div class="dossier_titre">
    <h2>Horizon 2020, nouvelles opportunités</h2>
</div>

and you can apply the following CSS:

.zone_33 {
    width: 238px;
    padding: 0px;
    margin: 0px;
}

.zone_33 .dossier_titre {
    margin: 0px 0px 20px 0px;
}

.zone_33 h2 {
    color: #616263;
    font-size: 150%;
    font-weight: lighter;
    padding: 0px 0px 12px 0px;
    background: none;
    border-bottom: 1px solid grey;
    display: table-cell;
    text-transform: uppercase;
}

.zone_33 .dossier_titre:after {
    content: "";
    display: table-cell;
    width: 100%;
}

For the <h2> element, set display: table-cell, and add a pseudo-element after .dossier_titre (the containing block for the header/title element). The pseudo-element is also a table-cell and has a width of 100% (this is the key).

Also, since h2 is no longer a block element, add your margins to .dossier_titre to maintain the visual spacing in our layout.

How This Works
I am creating a two-cell table with the second cell (the pseudo-element) having a width of 100%. This triggers the browser to calculate the shrink-to-fit width for the first cell (h2) that contains the title text. The first cell's width is thus the minimal needed to display the text. The bottom border is as long as the longest text line in the text block within the table-cell.

Limitations
table-cell is not supported in IE7 without a hack, but the work-around is fairly well known and can be found if needed.

If the title had many short words, you might get the line breaking in unexpected places. You would need to insert &nbsp to keep specific words together as needed.

Fiddle: http://jsfiddle.net/audetwebdesign/h34pL/


This works on Chrome.

h2 {
   width: fit-content;
}