[CSS]画像の天地の上限を設定し、垂直方向の中央に配置するCSSのテクニック
Post on:2011年11月29日
sponsorsr
Responsive Web Design用にサイズを100%で設置した画像の天地の上限を設定し、垂直方向の中央に配置するCSSのテクニックを紹介します。

Responsive Web Design: Overflow Image with vertical centering
[ad#ad-2]
デモ
デモでは1000x666pxの大きい画像が配置されており、表示サイズを変更しても画像は設定された高さの上限を超えることなく、常に垂直方向の中央に配置されるようになっています。
画像はどのサイズでも、テントウムシが中央にいます。

デモページ:幅1200pxで表示

デモページ:幅800pxで表示

デモページ:幅480pxで表示
実装
実装のイメージ
画像のサイズは100%で設定し、高さ・幅の上限は画像を内包するdiv要素で設定します。
また、垂直方向の中央に配置するために、「overflow: hidden;」を使って余剰分を隠します。

実装のイメージ:下だけクリップ
このままでは余剰分を隠す際、画像の下部を削るだけになってしまうため、jQueryを使用して天地両方から削るようにします。

実装のイメージ:天地均等にクリップ
[ad#ad-2]
HTML
画像はimg要素で配置し、div要素で内包します。
<div class="image-wrap" id="wrapper">
<img src="path/to/your/image.jpg" alt="your image">
</div>
CSS
上限の高さを450pxに設定します。
.image-wrap {
max-height: 450px;
overflow: hidden;
max-width: 800px;
-webkit-transition: max-width .5s ease-out; /* Saf3.2+, Chrome */
-moz-transition: max-width .5s ease-out; /* FF4+ */
-ms-transition: max-width .5s ease-out; /* IE10? */
-o-transition: max-width .5s ease-out; /* Opera 10.5+ */
transition: max-width .5s ease-out;
}
.image-wrap img {
width: 100%;
-webkit-transition: margin-top .5s ease-out; /* Saf3.2+, Chrome */
-moz-transition: margin-top .5s ease-out; /* FF4+ */
-ms-transition: margin-top .5s ease-out; /* IE10? */
-o-transition: margin-top .5s ease-out; /* Opera 10.5+ */
transition: margin-top .5s ease-out;
}
@media only screen and (min-width: 1160px) {
.image-wrap { max-width: 1000px; }
}
JavaScript
「jquery.js」を外部ファイルとし、下記のスクリプトを記述します。
※jQuery1.7の.on()を使用しています。1.7以前の場合は.bind()にして利用してください。
$(document).ready(function() {
var imageHeight, wrapperHeight, overlap, container = $('.image-wrap');
function centerImage() {
imageHeight = container.find('img').height();
wrapperHeight = container.height();
overlap = (wrapperHeight - imageHeight) / 2;
container.find('img').css('margin-top', overlap);
}
$(window).on("load resize", centerImage);
var el = document.getElementById('wrapper');
if (el.addEventListener) {
el.addEventListener("webkitTransitionEnd", centerImage, false); // Webkit event
el.addEventListener("transitionend", centerImage, false); // FF event
el.addEventListener("oTransitionEnd", centerImage, false); // Opera event
}
});
sponsors











