Front-End & Daily

JS to align images of different aspect ratios horizontally with equal height

JS to align images of different aspect ratios horizontally with equal height

Introducing JavaScript code that can align images with different aspect ratios at the same height and arrange them horizontally for gallery pages.

By the way, the main visual is a rabbit I used to keep at my parents' house.

Table of Contents

Sample

Images are arranged with equal height using JS. Each one is an image.

(Check it out in dev tools!)

Supports 5 columns, etc.

For CSS, either Flexbox or float is fine. The above uses Flex, and the below uses float.

Also, here is a page that actually uses this layout.

Konomi Sakamoto OFFICIAL HOMEPAGE

HTML

Set the parent element as .galleryheight, the child elements as .col, and place img tags inside them.

<ul class="galleryheight">
	<li class="col"><img src="img/img_240_480.png"></li>
	<li class="col"><img src="img/img_680_240.png"></li>
	<li class="col"><img src="img/img_360_360.png"></li>
	<li class="col"><img src="img/img_800_120.png"></li>
	<li class="col"><img src="img/img_680_240.png"></li>
	<li class="col"><img src="img/img_240_480.png"></li>
	<li class="col"><img src="img/img_360_360.png"></li>
	<li class="col"><img src="img/img_240_480.png"></li>
	<li class="col"><img src="img/img_360_360.png"></li>
</ul>

CSS

This is a very standard Flex layout.

Or rather, please create a very standard column layout.

Probably any number of columns will be fine.

.galleryheight {
	display: flex;
	flex-wrap: wrap;
	margin: 0 0 -2%;
	padding: 0;
	list-style: none;
}
.galleryheight .col {
	width: 32%;
	margin: 0 2% 2% 0;
}
.galleryheight .col:nth-child(3n) {
	margin-right: 0;
}
.galleryheight .col img {
	width: 100%;
}

JS

We will introduce both the jQuery version and the native JavaScript version of JS.

When there are about 1000 images, a difference of about 0.1 to 0.05 seconds was observed.

Processing speed comparison demo for jQuery and JavaScript

jQuery Version

$(function(){
	//親要素の幅
	let parentWidth = $(".galleryheight").width();
	//子要素
	let elm = $(".galleryheight .col");
	//小要素の数だけwhile文 (forではうまく作れず)
	let elmLen = elm.length;
	let i = 0;
	while(i < elmLen){
		//初めの(左端の)offset (四捨五入)
		let offset = Math.round(elm.eq(i).offset().top);
		//計算用
		let colWidth = 0;
		let imgWidth = 0;
		//その行の配列
		let arr=[];
		//左端と同じoffsetが続く間while文
		while(i < elmLen && offset == Math.round(elm.eq(i).offset().top)){
			//該当の子要素
			let target = elm.eq(i);
			let targetWidth = target.width();
			let targetImg = target.find("img");
			//imgの幅
			let width = targetImg.width();
			//幅が0の場合はスルー
			if(width > 0){
				let height = targetImg.height();
				//試しに高さを1にしてみたときの幅 (以降 テスト幅)
				let testWidth = width / height;
				//配列に追加
				arr.push([target, testWidth]);
				//子要素の幅を加算
				colWidth += targetWidth;
				//テスト幅を加算
				imgWidth += testWidth;
			}

			++i;
		}

		//その行の数(カラム数)だけfor文
		let arrLen = arr.length;
		for(var j = 0; j < arrLen; j++){
			//該当要素のテスト幅 ÷ テスト幅の合計 × 100%で割合を出せるが
			//子要素の幅の合計 ÷ 親要素の幅の合計を掛け、少数第二位で切り捨てにし調整
			let newWidth = Math.floor((arr[j][1] / imgWidth * 100 * colWidth / parentWidth) * 100) / 100;
			//セット
			arr[j][0].css("width", newWidth + "%");
		}
	}
});

JavaScript Version

//親要素の幅
let parentWidth = document.querySelector(".galleryheight").clientWidth;
//子要素
let elm = document.querySelectorAll(".galleryheight .col");

//offset取得用
let scrollTop = window.pageYOffset || document.documentElement.scrollTop;

//小要素の数だけwhile文
let elmLen = elm.length;
let i = 0;
while(i < elmLen){
	//初めの(左端の)offset (四捨五入)
	let offset = Math.round(elm[i].getBoundingClientRect().top + scrollTop);
	//計算用
	let colWidth = 0;
	let imgWidth = 0;
	//その行の配列
	let arr=[];
	//左端と同じoffsetが続く間while文
	while(i < elmLen && offset == Math.round(elm[i].getBoundingClientRect().top + scrollTop)){
		//該当の子要素
		let target = elm[i];
		let targetWidth = target.clientWidth;
		let targetImg = target.getElementsByTagName("img")[0];
		//imgの幅
		let width = targetImg.clientWidth;
		//幅が0の場合はスルー
		if(width > 0){
			let height = targetImg.clientHeight;
			//試しに高さを1にしてみたときの幅 (以降 テスト幅)
			let testWidth = width / height;
			//配列に追加
			arr.push([target, testWidth]);
			//子要素の幅を加算
			colWidth += targetWidth;
			//テスト幅を加算
			imgWidth += testWidth;
		}

		++i;
	}

	//その行の数(カラム数)だけfor文
	let arrLen = arr.length;
	for(var j = 0; j < arrLen; j++){
		//該当要素のテスト幅 ÷ テスト幅の合計 × 100%で割合を出せるが
		//子要素の幅の合計 ÷ 親要素の幅の合計を掛け、少数第二位で切り捨てにし調整
		let newWidth = Math.floor((arr[j][1] / imgWidth * 100 * colWidth / parentWidth) * 100) / 100;
		//セット
		arr[j][0].style.width = newWidth + "%";
	}
}

I hope this is helpful.

Customizations are also possible, so please feel free to comment.

Comments

After reviewing the content, we will publish it, omitting personal information.

Enter your name and email address

Please enter if you would like a reply by email.

The personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and click "Send".

If this was helpful, we appreciate your support!
All support received will be used for childcare.

Send support via OFUSE


Or support us by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

楽天市場

Yahoo!ショッピング

PR

As an Amazon Associate, "Ken" earns income from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark