css - Restrict border width to text width in a block element -


i have <h2> title fixed <div> (238px). when page rendered, browser manage line breaks title make text fit width (238px).

but width property of h2 element still 238px, no matters line breaks are.

i want set border-bottom under text, , not under full width of h2 element, , don't know how achieve using css.

you can see mean here : http://jsfiddle.net/np3rj/2/

thanks

if willing use display: table-cell, , pseudo-elements, can have pretty solution (with minor limitations).

the html not change:

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

and can apply 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 <h2> element, set display: table-cell, , add pseudo-element after .dossier_titre (the containing block header/title element). pseudo-element table-cell , has width of 100% (this key).

also, since h2 no longer block element, add margins .dossier_titre maintain visual spacing in our layout.

how works
creating two-cell table second cell (the pseudo-element) having width of 100%. triggers browser calculate shrink-to-fit width first cell (h2) contains title text. first cell's width minimal needed display text. bottom border long longest text line in text block within table-cell.

limitations
table-cell not supported in ie7 without hack, work-around known , can found if needed.

if title had many short words, might line breaking in unexpected places. need insert &nbsp keep specific words needed.

fiddle: http://jsfiddle.net/audetwebdesign/h34pl/


Comments