
さまざまな比率の画像を同じサイズにレイアウトする際に、長辺側を100%として縦横中央に配置するCSSを作成しました。
一覧ページのサムネイル画像をレイアウトする時などに役立ちますね!
その他に、短辺側を100%として長辺はトリミングするパターンも作成しました。
こちらは画像の空きを作りたくない時などに便利です。(意図しないかしょから画像がきれてしまいますが、、、)
デモサイトはこちら
長辺を100%として縦横中央に配置
こちらは4対3で表示される枠で作成しています。
枠を指定しているのは.full-full:afterのpadding-top: 75%;です。
正方形にしたい場合はpadding-top: 100%;にしてください😊
after(擬似要素)を使用しているのでcontent: ‘ ‘;を忘れずに!!
HTML
<div class="full-full">
<img src="img/main_img.jpg" width="800" height="450">
</div>
<div class="full-full">
<img src="img/main_img02.jpg" width="800" height="450">
</div>
CSS
.full-full{
margin-bottom: 30px;
width: 100%;
max-width: 500px;
background-color: #eee;
overflow: hidden;
position: relative;
}
.full-full img{
position: absolute;
width: auto;
height: auto;
top: 50%;
left: 50%;
max-width: 100%;
max-height: 100%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.full-full:after{
display: block;
padding-top: 75%;
content: '';
}
短辺が100%表示され長辺はトリミングする
こちらは短辺が100%になり長辺はトリミングされる場合のCSSです。
横長の画像の場合は短辺となるheightを100%にしてwidhtをautoに、縦長の画像の場合はその逆を指定します。
HTML
<div class="height-full">
<img src="img/main_img.jpg" width="800" height="450">
</div>
<div class="width-full">
<img src="img/main_img02.jpg" width="800" height="450">
</div>
CSS
.height-full{
margin-bottom: 30px;
width: 100%;
max-width: 500px;
overflow: hidden;
position: relative;
}
.height-full img{
position: absolute;
width: auto;
height: 100%;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.height-full:after{
display: block;
padding-top: 75%;
content: '';
}
.width-full{
margin-bottom: 30px;
width: 100%;
max-width: 500px;
overflow: hidden;
position: relative;
}
.width-full img{
position: absolute;
width: 100%;
height: auto;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.width-full:after{
display: block;
padding-top: 75%;
content: '';
}