cssで複数行テキストの行ごとに背景色を適用する方法
複数行にまたがるテキストを表示する際、以下のように各行の長さに合わせて背景色を付けたい場面が多々あるかと思います。
display: inline; を指定した場合
display: inline; を指定することで近いことは出来ますが、行ごとのテキストの左右に
均等な余白を付けることができません。
・html
1 |
<p class="copy01">コピーテキストテキストテキスト<br />テキストテキストテキストテキストテキスト</p> |
・css
1 2 3 4 5 6 7 8 9 |
.copy01 { font-size: 3rem; font-weight: bold; display: inline; padding: 0.3em 0.5em; line-height: 3; background-color: #7CD0FF; color: #FFF; } |
また、行ごとをpやspanタグで囲む方法もありますが、極力タグを増やしたくない…
box-decoration-break: clone; を使う
box-decoration-break: clone; を指定することで、
複数行のテキストの余白を調整することが出来ます。
・html
1 |
<p class="copy01">コピーテキストテキストテキスト<br />テキストテキストテキストテキストテキスト</p> |
・css
1 2 3 4 5 6 7 8 9 10 11 |
.copy01 { font-size: 3rem; font-weight: bold; display: inline; box-decoration-break: clone; -webkit-box-decoration-break: clone; padding: .3em; line-height: 2.5; background-color: #7CD0FF; color: #FFF; } |
※Firefox以外のモダンブラウザはベンダープレフィックス-webkit-が必要です。
IEには非対応となっています。
position と一緒に使用する際は注意が必要
・css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
.copy01 { font-size: 3rem; font-weight: bold; display: inline; box-decoration-break: clone; -webkit-box-decoration-break: clone; padding: .3em; line-height: 2.5; background-color: #7CD0FF; color: #FFF; position: absolute; top: 30%; right: 0%; } |
上記のようにbox-decoration-break: clone; とposition: absolute; を
一緒に記述すると、意図しない表示になってしまいます。
position で配置する際には、position指定用のdivで複数行テキストを囲む必要があります。
・html
1 2 3 4 5 |
<div class="bg01"> <div class="copy_box01"> <p class="copy01">コピーテキストテキストテキスト<br />テキストテキストテキストテキストテキスト</p> </div> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
.bg01 { height: 475px; background: url(images/bg01.jpg) no-repeat 0px 0px; position: relative; } .copy_box01 { position: absolute; top: 30%; right: 0%; } .copy01 { font-size: 3rem; font-weight: bold; display: inline; box-decoration-break: clone; -webkit-box-decoration-break: clone; padding: 0.3em 0.5em; line-height: 3; background-color: #FFF; } |