【CSS】擬似要素の位置調整
- :beforeでつけたiconと文字のラインを揃える
- 1のバージョン
- 2のバージョン
- 2のバージョンで正方形や正円を作る
- ちょっと改良
- 1のバージョンで無理やり正円作る
- 正方形・正円作るならposition:absolute;がおすすめ
:beforeでつけたiconと文字のラインを揃える
text-align:center;
とvertical:text-top;
を使用するposition:absolute
とtop
とleft
を使用するfont-size
で文字の大きさとiconのサイズを揃える(非推奨)
1のバージョン
scssで記載してます。
ul li{ list-style-type:none; //リストマーク非表示 &:before{ content: '\f006'; //はてなブログで使えるicon font-family: blogicon; font-size: .6rem; //iconサイズ /*こっから位置調整*/ text-align: center; //横方向の>中央寄せ vertical-align: text-top; //縦方向の>の中央寄せ margin-right: .3rem; //親要素との距離 } }
2のバージョン
scssで記載してます。
ul li{ list-style-type:none; position: relative; &:before{ content: '\f006'; font-family: $blog; font-size: .6rem; /*こっから位置調整*/ text-align: center; // 横方向の>のセンターよせ position: absolute; top: .1rem; //縦の位置 left: -1.5rem; //横の位置 } }
2のバージョンで正方形や正円を作る
1のバージョンでも作れないことはないですが、padding
で丸の縦横比を調整するので面倒だし難しいです。
なのでwidth
とheight
の効く2のバージョン(position:absolute
)でやっていきます。
完成形
Sass(SCSS)
数字の方でなく>の方のコードになります。
ul li{ list-style-type:none; position: relative; &:before{ content: '\f006'; font-family: blogicon; color: white; font-size: .6rem; text-align: center; // 横方向の>のセンターよせ position: absolute; top: .1rem; //縦の位置 left: -1.5rem; //横の位置 background: #2C687A; //円の色 border-radius: 50%; //正円を作る width:1.1rem; //円の横サイズ height:1.1rem; //円の縦サイズ padding: .1rem; // >と円の間隔、円のサイズも変わる } }
ちょっと改良
>
の位置調整用にline-height
追加。box-shadow
とかは好みで。- 円のサイズを少し大きめにしたので親に
margin-bottom
追加。
Sass(SCSS)
ul li{ list-style-type: none; position: relative; margin-bottom: .2rem; //文字の下間隔少し開ける &:before{ position:absolute; left: -2rem; //円の位置 content: '\f006'; font-family: blogicon; color: white; font-size: .6rem; background: #2C687A; border-radius: 50%; //円を作る width: 1.2rem; //円のサイズ height: 1.2rem; //円のサイズ padding: .1rem; // >と円の間隔円のサイズも変わる text-align: center; // 横方向の>のセンターよせ line-height: 1.8; //>の位置 box-shadow:1px 1px 2px 1px rgba($dimgray, .3); } }
見た目
1のバージョンで無理やり正円作る
正円になってるか微妙なところですがpadding
の値を調整して正円っぽくしました。
上下のpadding
の値が違うのは>
の位置を中央に配置するためです。
完成形
Sass(SCSS)
ul li{ list-style-type:none; &:before{ content: '\f006'; font-family: blogicon; color: white; font-size: .6rem; background: #2C687A; border-radius: 50%; //円を作る text-align: center; // 横方向の>のセンターよせ vertical-align: text-top; //縦方向の>の中央寄せ margin: 0 .3rem; //親要素との距離 padding: .22rem .5rem .33rem; //正円っぽい? } }
正方形・正円作るならposition:absolute;がおすすめ
widthとheightを同じ数値にすれば簡単に正方形・正円になるので、正方形と正円を作るならposition:absolute;
を使用する方をおすすめします。
他にもいいやり方あればぜひ教えてください!