0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CSS ::before / ::after 疑似要素とcontentプロパティの使い方完全整理

Last updated at Posted at 2025-05-01

はじめに

CSSの疑似要素::before::afterを使えば、HTMLを変更せずに視覚効果を追加できます。

# ①疑似要素とは?
::before / ::afterは、ある要素の前後に追加の内容を表示できるCSSの機能です。
主に装飾視覚的な演出に使われます。

::beforeの例

.element::before {
    content: '*';
    color: gold;
}

→要素の先頭に★が追加されます。

::afterの例

.element::after {
    content: '→';
    color: red;
}

→要素の末尾に矢印が追加されます。

②contentプロパティの使い方と注意点

基本

content: '';
  • 疑似要素を表示させるにはcontentの指定が必須
  • 空文字``でもOK。主に装飾だけ表示したいときに使います。

contentに文字列や記号を指定する

.item::before {
    content: 'New!';
    color: green;
}

→「New!」という文字が追加されます。

contentに数字を指定したいときの注意点

.item::before {
    content: '1.';
}

→「1.」がそのまま表示されます。

  • ポイントは必ずクォート('や")で囲んで文字列として扱う!
content: 1; /* ←これはNG(無効) */

③よく使う実例

1.下線アニメーション付きリンク

.readmore a {
    position: relative;
}

.readmore a::after {
    content: '';
    position: absolute;
    height: 1px;
    width: 100%;
    left: 0;
    bottom: 0;
    background: #333;
    transition: all 200ms ease;
}

.readmore a:hover::after {
    opacity: 0;
    transform: translateY(3px);
}

2.三角形の矢印を表示する(borderで作る)

.arrow:before {
    content: '';
    border-style: solid;
    border-width: 6px 0 6px 8px;
    border-color: transparent transparent transparent #333;
    position: absolute;
    top: 50%;
    left: 0;
    margin-top: -6px;
}

3.番号付きリスト風の表示

.step::before {
    content: '1. ';
    font-weight: bold;
}

④補足: 関連プロパティの役割まとめ

IMG_7868.jpeg

⑤まとめ

  • ::before / ::after を使えばHTMLをいじらずに装飾できる
  • content の指定がなければ疑似要素は表示されない
  • 数字や記号を表示する場合もクォートで囲む必要あり
  • 実務では下線・矢印・ラベルなど装飾演出に頻出
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?