2022.08.30

HTML・CSS

linear-gradientを利用した文字の下線

background-imageプロパティのlinear-gradientを利用して複数行の文字に下線を引きます。複数行に対応させるため、inline要素に適用します。
デモページはこちら

以下のhtml構造で確認します。

<p>to bottom(180deg)</p>
<div class="div-parent">
  <span class="span-child-01">linear-gradientを利用した文字の下線<br>inline要素に適用して複数行に対応</span>
</div>
<p>to bottom(180deg)※下線位置を2px上に調整</p>
<div class="div-parent">
  <span class="span-child-02">linear-gradientを利用した文字の下線<br>inline要素に適用して複数行に対応</span>
</div>
<p>to right(90deg)</p>
<div class="div-parent">
  <span class="span-child-03">linear-gradientを利用した文字の下線<br>inline要素に適用して複数行に対応</span>
</div>
<p>to right(90deg)※下線位置を2px上に調整</p>
<div class="div-parent">
  <span class="span-child-04">linear-gradientを利用した文字の下線<br>inline要素に適用して複数行に対応</span>
</div>

linear-gradienの基本的な記述は以下になります。

background-image: linear-gradient(方向, 開始色, 中間色, 終了色);

方向は「to right」のようにtoに続けてキーワードを指定するか、「90deg」のようにdegで角度を指定します。方向の指定を省略すると初期値の「to bottom(180deg)」が適用され、上から下にグラデーションがかかります。

開始色、中間色、終了色は後ろに「#eae5d6 60%」のように経由点を指定することができます。
「transparent 60%, #eae5d6 60%」のように開始色と終了色の経由点を同じにすると、グラデーションではなくシマシマ模様になります。このシマシマ模様が文字の下線に利用できます。
なお、不要であれば中間色は省略できます。

CSSは以下になります。backgroundプロパティにショートハンドで指定する方法と、background-imageプロパティを使う方法があります。また、グラデーションの方向「to bottom(180deg)」と「to right(90deg)」で記述を分けています。

background-positionで「left bottom 2px」のように記述すれば、下線の縦方向の位置を2px上に調整できます。

.div-parent {
  line-height: 1.5;
  min-height: 100px;
  margin: 0 0 1em;
  background-color: #fff;
}

//to bottom(180deg)
.span-child-01 {
  background: linear-gradient(transparent 60%, #eae5d6 60%);
}
.span-child-02 {
  background: linear-gradient(transparent 60%, #eae5d6 60%) left bottom 2px;
}

//to right(90deg)
.span-child-03 {
  background-image: linear-gradient(to right, #eae5d6, #eae5d6);
  background-repeat: no-repeat;
  background-position: left bottom;
  background-size: 100% 40%; //幅・高さ
}
.span-child-04 {
  background-image: linear-gradient(to right, #eae5d6, #eae5d6);
  background-repeat: no-repeat;
  background-position: left bottom 2px;
  background-size: 100% 40%; //幅・高さ
}

関連記事

2024.09.13

HTML・CSS

疑似クラス:has()を利用した余白と色の調整

疑似クラスの:has()を利用して、liタグの余白と色を調整をします。デモページはこちら 共通のCSSは以下になります。通常時はulタグにgap: 60pxを指…

2024.08.15

HTML・CSS

box-decoration-breakでテキストの背景色を設定

box-decoration-breakプロパティでテキストに背景色を設定します。複数行の文字に対応でき、改行も問題ありません。デモページはこちら 以下のhtm…

2024.08.19

HTML・CSS

縦書き文字の配置について

縦書きの文字を写真の左上・左中・左下・右上・右中・右下に配置します。デモページはこちら 以下のhtml構造で確認します。 CSSはpositionとtransf…

2021.09.13

HTML・CSS

nth-childの関数表記でカラムごとにCSSを設定

デモページはこちら 3カラムで複数行のコンテンツに、カラムごとに背景色のCSSを設定します。3カラムの場合、1カラム目は:nth-child(3n + 1)、2…

2020.11.04

HTML・CSS

inline要素のマージン

デモページはこちら inline要素にCSSでマージンを設定した場合の挙動です。以下のhtml構造のspanタグでテストします。 inline要素に左右のマージ…

上に戻る