CSS - attr()

概要

形式attr(<attr-name> <attr-type>? [, <fallback>])
値の詳細<attr-type> = <attr-unit> | string | type(<syntax>)
サポートhttps://caniuse.com/?search=attr()

説明

要素の属性値を参照します。Chrome 133 ですべてのプロパティに対応しましたが、他のブラウザではまだ content のみで使用可能です。

<attr-name>
要素の属性名を指定します。
<attr-unit>
値の単位を em, px, deg などで指定します。

<syntax>
値の型を type(<color>) のように指定します。型には string, color, url, integer, number, length, angle, time, frequency を指定します。Chrome 133 でサポートされました。(サポート状況)
<fallback>
値の取得に失敗した場合の代替値を指定します。Chrome 133 でサポートされました。(サポート状況)

使用例

content で使用する例

CSS
a[href]::after {
  font-size: 80%;
  content: " (" attr(href) ")";
}
HTML
<a href="http://www.tohoho-web.com">とほほのWWW入門</a>
表示
とほほのWWW入門

content 以外で使用する例

CSS
[data-size] {
  font-size: attr(data-size px);
}
[data-color] {
  color: attr(data-color type(<color>), blue);
}
HTML
<div data-size="64">AAAA</div>
<div data-color="red">AAAA</div>
表示
AAAA
AAAA

関連項目

content

リンク