初心者のためのCSSによる画像の中央揃え
CSSで画像を中央に配置する方法をご紹介します!
この記事では、横方向(水平)の中央揃えと縦方向(垂直)の中央揃えの両方について解説しており、初心者の方でも理解しやすいように具体的な例(サンプル)やコツもあわせてご紹介します。
関連項目
CSSによる画像の横方向(水平)中央揃え
画像そのものにCSSを適用する方法:display: block
とmargin-left: auto
margin-right: auto
<div class="container">
<img class="image" src="image-source.jpg" alt="画像">
</div>
.container {
background-color: orange;
}
.image {
width: 200px;
display: block;
margin-left: auto;
margin-right: auto;
}

左右に余白がある親要素にtext-align: center
を指定する
<div class="container">
<img class="image" src="image-source.jpg" alt="画像">
</div>
.container {
background-color: orange;
text-align: center; /* 左右に余白がある親要素の横幅を基準に、子要素のテキストや画像などインライン要素を中央に配置します */
}
.image {
width: 200px;
vertical-align: top;
}

左右に余白がある親要素にdisplay: flex
とjustify-content: center
を指定する
<div class="container">
<img class="image" src="image-source.jpg" alt="画像">
</div>
.container {
background-color: orange;
display: flex;
justify-content: center; /* 子要素を水平方向(横方向)の中央に配置します */
}
.image {
width: 200px;
}

CSSによる画像の縦方向(垂直)中央揃え
親要素にdisplay: flex
とalign-items: center
を指定する
<div class="container">
<img class="image" src="image-source.jpg" alt="画像">
</div>
.container {
background-color: orange;
height: 200px;
display: flex;
align-items: center; /* 子要素を縦方向(垂直)の中央に配置します */
}
.image {
width: 200px;
}

親要素と子要素にposition
およびtransform
プロパティを使用する
<div class="container">
<img class="image" src="image-source.jpg" alt="画像">
</div>
.container {
background-color: orange;
height: 200px;
position: relative;
}
.image {
width: 200px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}

CSSによる画像の横方向(水平)・縦方向(垂直)中央揃え
左右に余白がある親要素にdisplay: flex
、justify-content: center
およびalign-items: center
を指定する
<div class="container">
<img class="image" src="image-source.jpg" alt="画像">
</div>
.container {
background-color: orange;
height: 200px;
display: flex;
justify-content: center; /* 子要素を水平方向(横方向)の中央に配置します */
align-items: center; /* 子要素を垂直方向(縦方向)の中央に配置します */
}
.image {
width: 200px;
}

親要素と子要素にposition
およびtransform
プロパティを使用する
<div class="container">
<img class="image" src="image-source.jpg" alt="画像">
</div>
.container {
background-color: orange;
height: 200px;
position: relative;
}
.image {
width: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
