CSS辞典 attr()関数の解説
属性値を取得するattr()関数の使用方法と使用例、メールアドレスの@前後を関数で挿入するサンプルコードを記載
概要・使用方法
{ プロパティ:attr(属性)}
「attr()関数」は選択要素の属性値取得しCSSで使うことができます。主に::beforeと::after疑似要素で、contetプロパティと一緒に使用します。
属性
属性名 | 属性値を取得した属性名 |
サンプルコード1
hrefプロパティの値をattr()関数で取得して、::after疑似要素で表示。
<!DOCTYPE html>
<html lang="ja">
<head>
<title>CSS attr関数サンプルページ</title>
<meta charset="uft-8">
<style>
.link::after{
content: attr(href);
}
</style>
</head>
<body>
<p><a href="http://google.com" class="link">URL:</a></p>
</body>
</html>
実行結果
chromeブラウザ実行結果

Firefox ブラウザ実行結果

edgeブラウザ実行結果

operaブラウザ実行結果

サンプルコード2
data-*属性でメールアドレスの@の前と後ろの部分を記述して、attr()関数で取得し前後の疑似要素でメールアドレスを挿入しています。
<!DOCTYPE html>
<html lang="ja">
<head>
<title>CSS attr関数サンプルページ</title>
<meta charset="uft-8">
<style>
.email::before{
content: attr(data-account);
}
.email::after{
content: attr(data-domain);
}
</style>
</head>
<body>
<span class="email" data-account="info" data-domain="example.com">@</span>
</body>
</html>
実行結果
@chromeブラウザ実行結果

Firefox ブラウザ実行結果

edgeブラウザ実行結果

operaブラウザ実行結果
