擬似要素:before / after
擬似要素
- HTMLに記述せずCSSで擬似的に作成される要素であるため、「擬似要素」と呼ばれています
- 擬似要素には多くの種類がありますが、その中でもよく使用される擬似要素はbeforeとafterです
before / afterとは
- 要素の前後に擬似要素を作成する指定方法です
before / afterの使い方
- 要素やclass名、id名などのあとに::before、::afterと記述します
- beforeとafterの前にはコロン(:)の記述が2つ必要です
- スタイルの中には「content」の指定が必要です
- content: ""; の中身は空白でも大丈夫ですが、記号やテキストを表示したいときにはcontentのクオーテーションの中に表示したい内容を記述します
p::before { content: ""; } p::after { content: ""; }
before / afterの違い
- beforeは要素の直前、afterは要素の直後に表示されます
<p>テキスト</p>
p::before { content: "要素の直前に表示されます"; color: red; } p::after { content: "要素の直後に表示されます"; color: blue; }
例 A
<div class="content"> <ul> <li class="new">ジャケット - 10,000円</li> <li>Yシャツ - 4,800円</li> <li>Tシャツ - 2,800円</li> <li class="new">バッグ - 8,000円</li> </ul> </div><!-- /.content -->
body { font-family: sans-serif; line-height: 2.0; padding: 2rem; } .new::after { content: "NEW!"; margin-left: 5px; padding: 5px; border-radius: 3px; background: #f99; color: #fff; font-size: .75rem; }
例 B
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <title>カギカッコを使った引用文 デモ</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="wrapper"> <blockquote> <p> 「天は人の上に人を造らず人の下に人を造らず」と言えり。 されば天より人を生ずるには、万人は万人みな同じ位にして、生まれながら貴賤上下の差別なく、 万物の霊たる身と心との働きをもって天地の間にあるよろずの物を資り、 もって衣食住の用を達し、自由自在、互いに人の妨げをなさずしておのおの安楽にこの世を渡らしめ給うの趣意なり。 </p> </blockquote> </div><!-- /.wrapper --> </body> </html>
@charset "UTF-8"; /* ---------------------------------------- reset ---------------------------------------- */ *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; } /* ---------------------------------------- body ---------------------------------------- */ body { color: #333; font-size: 16px; font-family: serif; line-height: 2; } /* ---------------------------------------- layout ---------------------------------------- */ .wrapper { max-width: 600px; margin: 20px auto; } blockquote { position: relative; padding: 2em; } blockquote::before, blockquote::after { content: ''; width: 40px; height: 40px; position: absolute; } blockquote::before { border-top: 2px solid #ccc; border-left: 2px solid #ccc; top: 0; left: 0; } blockquote::after { border-bottom: 2px solid #ccc; border-right: 2px solid #ccc; bottom: 0; right: 0; }