CSSを用いてウェブページ上の要素を中央に配置する方法を簡単にまとめます。
水平方向の中央配置
インライン要素
.center-text {
text-align: center;
}テキストやインライン要素(例:<span>、<a>)を含む要素内で使用
ブロック要素
ブロックレベル要素(例:<div>)で使用。
要素に固定幅を設定する必要あり。
.center-element {
margin: 0 auto;
width: 50%
}垂直方向の中央配置
Flexboxを使用した方法
.center-flexbox {
display: flex;
align-items: center;
justify-content: center;
height: 100vh; /* コンテナの高さをビューポートの高さに設定 */
}Flexboxコンテナ内のアイテムを垂直および水平方向の中央に配置
Gridを使用した方法
.center-grid {
display: grid;
place-items: center;
height: 100vh; /* コンテナの高さをビューポートの高さに設定 */
}この方法は、CSS Gridを使用して要素を中央に配置
place-itemsプロパティは、短縮形でありalign-itemsとjustify-itemsの両方を中央に設定
