完璧ではありませんが、これまでに思いついた最善の解決策は、:after 疑似要素でマスクすることです。このようにして、テキスト全体に余分な要素は必要ありません。
例えば:
h1 {
/* A nice big spacing so you can see the effect */
letter-spacing: 1em;
/* we need relative positioning here so our pseudo element stays within h1's box */
position: relative;
/* centring text throws up another issue, which we'll address in a moment */
text-align: center;
/* the underline */
text-decoration: underline;
}
h1:after {
/* absolute positioning keeps it within h1's relative positioned box, takes it out of the document flow and forces a block-style display */
position: absolute;
/* the same width as our letter-spacing property on the h1 element */
width: 1em;
/* we need to make sure our 'mask' is tall enough to hide the underline. For my own purpose 200% was enough, but you can play and see what suits you */
height: 200%;
/* set the background colour to the same as whatever the background colour is behind your element. I've used a red box here so you can see it on your page before you change the colour ;) */
background-color: #990000;
/* give the browser some text to render (if you're familiar with clearing floats like this, you should understand why this is important) */
content: ".";
/* hide the dynamic text you've just added off the screen somewhere */
text-indent: -9999em;
/* this is the magic part - pull the mask off the left and hide the underline beneath */
margin-left: -1em;
}
<h1>My letter-spaced, underlined element!</h1>
以上です!
色や配置などを細かく制御したい場合はボーダーを使用することもできますが、幅が固定されていない限り、スパン要素を追加する必要があります。
たとえば、現在、h3 要素に 2px の文字間隔、中央揃えのテキスト、およびテキストと下線の間にスペースを追加した下線を必要とするサイトに取り組んでいます。私のcssは次のとおりです。
h3.location {
letter-spacing: 2px;
position: relative;
text-align: center;
font-variant: small-caps;
font-weight: normal;
margin-top: 50px;
}
h3.location span {
padding-bottom: 2px;
border-bottom: 1px #000000 solid;
}
h3.location:after {
position: absolute;
width: 2px;
height: 200%;
background-color: #f2f2f2;
content: ".";
text-indent: -9999em;
margin-left: -2px;
}
私のHTMLは次のとおりです。
<h3><span>Heading</span></h3>
ノート:
これは 100% きれいな CSS ではありませんが、少なくとも同じ結果を得るために HTML を変更したりハッキングしたりする必要がないことを意味します。
背景画像のある要素でこれを試す必要はまだないので、これを達成する方法はまだ考えていません。
テキストを中央に配置すると、ブラウザーはテキストを間違った場所に表示するため (テキストとその後の余分なスペースが考慮されます)、すべてが左に引っ張られます。text-indent 0.5em (上の例で使用した 1em の文字間隔の半分) を h1 要素 (:after 疑似要素ではない) に直接追加すると、これは修正されるはずですが、まだテストしていません。
フィードバックをお待ちしております。
ニール