≪ Today I learned. RSS購読
公開日
タグ
CSS
著者
ダーシノ(@bc_rikko)

新しいattr()では<color>や<length>などが取得できる

attr()という要素の属性の値を受け取ってCSS内で使用できる機能が進化して、<color><length>などを受け取れるようになった。

この仕様は、CSS Values and Units Module Level 5のWOrking Draftで策定されている。

新しいattr()の使い方

<div class="legacy" data-color="red" data-size="200"></div>

<div class="new" data-color="red" data-size="200"></div>
.legacy::after {
  content: attr(data-color);
  /* not working */
  background-color: attr(data-color);
  /* not working */
  width: attr(data-size);
}

.new::after {
  content: attr(data-color);
  background-color: attr(data-color type(<color>), inherit);
  width: attr(data-size px, fit-content);
}

デモ

redという文字が箱に入って2段になっている。下の箱は背景が赤色で、幅が伸びている。