Webサイトのコーディングをしていると、高さの違う画像を揃える機会が多々あります。
例えば、ブログリストでよく使います。
よく使うコーディング手法なので、ブログにまとめることにしました。
【CSS】高さの違う画像を揃える方法
完成形はこちらです。
See the Pen
Untitled by ゆーじろー (@yuji64)
on CodePen.
PCで見てもらえると分かりやすいです。
高さの違う画像の高さが揃っていることが分かるでしょう。
HTML
<ul class="list">
<li>
<div class="wrap">
<div class="image">
<img src="https://yujiromx.com/wp-content/uploads/2022/06/imac-gf77b1f9b2_640.jpg" alt="">
</div>
</div>
<h2>見出しが入ります。見出しが入ります。見出しが入ります。</h2>
</li>
<li>
<div class="wrap">
<div class="image">
<img src="https://yujiromx.com/wp-content/uploads/2021/01/font-326357_1920.jpg" alt="">
</div>
</div>
<h2>見出しが入ります。</h2>
</li>
<li>
<div class="wrap">
<div class="image">
<img src="https://yujiromx.com/wp-content/uploads/2022/06/icon_113280_256.png" alt="">
</div>
</div>
<h2>見出しが入ります。</h2>
</li>
</ul>
ポイントは、画像imgタグの上にdivを1つ用意することです。
divを用意する理由は、CSSの章で解説します。
CSS
.list {
max-width: 1000px;
margin: 100px auto;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
background-color: antiquewhite;
}
@media screen and (max-width: 768px) {
.list {
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
}
.list li {
width: calc((100% - 70px)/3);
}
@media screen and (max-width: 768px) {
.list li {
width: 100%;
}
}
.list li:not(:first-child) {
margin-left: 35px;
}
@media screen and (max-width: 768px) {
.list li:not(:first-child) {
margin: 30px 0 0 0;
}
}
.list li .wrap {
position: relative;
overflow: hidden;
padding-top: 100%;
background-color: #fff;
}
.list li img {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
-o-object-fit: cover;
object-fit: cover;
}
.list li h2 {
font-size: 18px;
margin: 20px 0;
line-height: 1.5;
}
imgの上にwrapクラスを用意して、そこでposition: relative;を使って基準を決めます。
そして画像の高さはheightでなくpadding-topを%で指定します。
こうすることで、レスポンシブした時に相対的に画像の高さが変わるようになります。
そしてwrapクラスの子要素のimgにposition: absolute;を指定しtopとleftで真ん中に持ってきます。
このスタイルを当てることで、どの画像サイズでも中心を基準に表示されるようになります。
あとはobject-fit: cover;を当てると、高さの違う画像が上手く表示されるようになりました。



