CSSでfloatやmargin&widthは使わずにブロック要素の中央寄せ・右寄せする方法
CSSでブロック要素を中央寄せする場合はwidth指定しつつ「margin:0 auto」を、右寄せする場合はfloat指定していた。この方法だと中央寄せの場合にPC / SPでwidthが変わる場合は面倒くさいし、右寄せの場合は親要素のmarginがずれるといった問題があり、もっと良い方法を無いか調べたのでメモ。
リファレンス
https://developer.mozilla.org/ja/docs/Web/CSS/justify-content
サンプル
https://taitan916.info/sample/flex-justify-content/
ソースコード
<html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ブロック要素の左寄せ・中央寄せ・右寄せ</title> <style> .left{ display: flex; justify-content: start; } .center{ display: flex; justify-content: center; } .right{ display: flex; justify-content: end; } </style> </head> <body> <div class="left">左寄せ</div> <div class="center">中央寄せ</div> <div class="right">右寄せ</div> </body> </html>
flex指定しつつjustify-contentプロパティで位置を設定するのが良さそう。
関連記事
-
-
特定のID / Classを持つタグの親要素に対してCSSを割り当てる方法
特定のID / Classを持つタグの親要素に対してCSSを割り当てたい。また、 ...
-
-
CodeIgniter4&Bootstrap&jQueryで簡易版お問い合わせページの作成
CodeIgniter4.4.4&Bootstrap&jQuer ...
-
-
jQuery無しで要素にアニメーション効果を設定する方法(animate.css)
あるサイトをWappalyzerで調査していた際に「animate.css」とい ...
-
-
CSSで親子関連のセレクターをネスト(入れ子)で指定する方法
CSSで親子関連のセレクターを指定する場合「.parent .child{}」の ...
-
-
「slick」でarrows(次に進む・前に戻るボタン)を設定しても表示されない場合の対応方法
「slick」で画像スライダーを表示する際にarrows(次に進む・前に戻るボタ ...