Search code examples
csscss-floatpositioning

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


Solution

  • 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/