Blog

jQueryで画像サイズを取得して上下左右中央配置にする方法

2018.02.23 コーディング

画像を中央配置する場合、以下のような形でpositionやmarginを使って指定することがあります。

HTML
<div>
<img src="images/img_01.png" alt="">
</div>
CSS
div {
  width: 100%;
  height: 500px;
  position: relative;
}

div img {
  width: 300px;
  height: 200px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -150px;
  margin-top: -100px;
}

昔からある一般的な方法ですし、どんなブラウザでも表示が安定しているためよく使う人もいるかもしれません。

しかしこの方法だと、画像のサイズを指定する必要があるため、使い回りなどできなくて若干不便です。

ということで今回は、jQueryで画像サイズを取得して上下左右中央に配置する方法をご紹介します。

jQueryで画像サイズを取得して上下左右中央配置にするソース

HTML
<div>
<img src="images/img_01.png" alt="">
</div>
CSS
div {
	width: 100%;
	height: 500px;
	position: relative;
}

div img {
	position: absolute;
	top: 50%;
	left: 50%;
}
jQuery
$(window).on("load resize",function(){

	var img = $('div img'),
	 imgWidth = img.width() / 2,
	 imgHeight = img.height() / 2;

	img.css({
		marginLeft: '-' + imgWidth + 'px',
		marginTop: '-' + imgHeight + 'px'
	});

});

jQueryで画像のwidthとheightの2分の1の値を取得し、ネガティブマージンとして指定しています。

画像サイズを個別に指定する必要がなくなるので、中央配置する画像に共通のクラスを付与しておくなどすれば、一発で指定できます。