• Skip to primary navigation
  • Skip to main content

Nagashima Laboratory

  • Home
  • Lecture
  • Note
  • Index
  • About

CSS 擬似要素(::before/::after)

::before/::after

フォルダ:css_sample_08

擬似要素とは

選択された要素の特定の部分にスタイル付けするときに使います。主に装飾に使用します。例えば、::beforeは、要素の前、::afterは後ろにスタイル付けできますが、CSSの設定次第で、表示させたい位置も含めて様々な設定ができます。

【準備】

  • 共通で使用するindex.htmlとstyle.cssを用意し、css_sample_08 フォルダの中に入れます(共通のデータとは、CSSの基本で使用したデータです。GitHubからもダウンロードできます)

▼index.htmlへの追記

<p class="mark">メイン要素(見出し、本文、画像などの主要な内容)が入ります</p>

▼style.cssへの追記

.mark::before {
  content: "《";
}

.mark::after {
  content: "》";
}

各プロパティの意味

  • content:ある要素に置き換えをするときに使います。beforeやafterなどの疑似要素は元々何も含まれていないので、beforeやafterに含めたいコンテンツを指定します。文字以外に画像なども指定できます。

【応用】アイコンを表示する

冒頭部分や行の最後にアイコンを表示されます。一度設定しておけば、HTML側で呼び出すだけでアイコンを表示できます。

▼index.htmlへの追記

<p class="arrow">冒頭に三角を表示します</p>
<p><a href="#" class="download">ダウンロード</a></p>

▼style.cssへの追記

.arrow::before {
  content: "";
  display: inline-block;
  border: 8px solid transparent;
  border-left: 8px solid blue;
}

.download::after {
  content: "Download";
  display: inline-block;
  background-color: darkblue;
  color: white;
  font-weight: bold;
  padding: 2px;
  margin-left: 10px;
  border-radius: 2px;
  font-size: 12px;
}

【応用】固定背景画像を設置する(iOS対応)

背景画像を固定する方法として、background-attachment: fixed; という設定方法がありますが、iOSではうまく動作しません。そこで擬似要素を用いて、背景画像を固定する方法を紹介します。

▼style.cssへの追記

body::before {
  content: "";
  background: url(images/bg.jpg) no-repeat;
  background-size: cover;
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: -1;
}

背景用の画像は過去のデータを使うか、手持ちの画像を使ってください

また、mainに高さがないと、背景が固定されていることがわかりにくいので、heightを調整してください。

▼style.cssへの追記

main {
  padding: 40px;
  height: 800px;
}

各プロパティの意味

  • display
    • block:ブロック要素のボックスを作ります
  • position:表示位置を設定します。
    • fixed:ブラウザに対して固定します
    • absolute:絶対な配置
    • relative:相対的な配置
  • top(left):positionと一緒に用いるプロパティです。表示位置を設定します。ほかに、bottomとrightがあります。
  • z-index:positionと一緒に用いるプロパティです。奥行き(重なり順)を設定します
  • 作成例:https://ngsm-syr.github.io/css_sample_08/
  • コード:https://github.com/ngsm-syr/css_sample_08

参考リンク

  • https://developer.mozilla.org/ja/docs/Web/CSS/Pseudo-elements
  • https://developer.mozilla.org/ja/docs/Web/CSS/::before
  • https://developer.mozilla.org/ja/docs/Web/CSS/::after
  • https://developer.mozilla.org/ja/docs/Web/CSS/display
  • https://developer.mozilla.org/ja/docs/Web/CSS/position
  • https://developer.mozilla.org/ja/docs/Web/CSS/content

2023-05-17 (Last Modified: 2023-05-18) Category: 資料 Tags:css

Copyright © 2023–2025 · Nagashima Sayuri Laboratory