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?

More than 3 years have passed since last update.

擬似要素を使って文字入りの簡単な装飾を作る方法

Last updated at Posted at 2021-03-13

たとえば見出しとかで、以下のような装飾を付けたくなったとき

sample.png
HTMLでspanタグなどを用いて作るのも一つの方法ですが、
擬似要素を用いることで余計なタグを書かずにスマートなマークアップをすることができます。

装飾を付けたいタグに擬似要素を追加する

sample.html
<h2>サンプルサンプルサンプル</h2>

上記タグに最初の画像のような、装飾を付けたい場合、

sample.css
html{
  font-size: 10px;
}
h2{
  font-size: 2rem;
}
//ここから下が擬似要素の記述
h2::before{
  content: "Q1";
  display: inline-block;
  font-size: 2rem;
  color: #fff;
  text-align: center;
  line-height: 60px;
  background: #cc4242;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 12px;
}

スタイルシートに上記の擬似要素を適用してあげればOK!

一応、表示結果は下記のようになる↓
sample02.png

今回の擬似要素の簡単な解説及びまとめ

取り敢えず、今回の設定で重要なところを抜粋すると(○○○の部分は任意の文字数字)

  • content: "○○○"; →ここで、擬似要素内で表示する文字を設定する。
  • display: inline-block; →擬似要素を横並びにするのに必要な設定。
  • text-align: center; line-height: ○○○px; →この2つが無いと文字が表示領域内で上下左右中央に来ない。line-heightは表示領域の高さと同じ値を入れてあげる。
  • border-radius: 50%; →今回は丸型でしたが、この記述無くすと四角にもなる。

擬似要素を使えると、記述の幅が広がるので覚えておいて損はしないと思います。
皆さんも、擬似要素を積極的に使っていきましょう!

 

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?