Pinterest風グリッドレイアウトを作る
目次
解説
使用技術
- TailwindCSS
- HTML
- JavaScript(画像遅延ロードで使用)
TailwindCSSでMasonryレイアウトを作る方法を紹介します。
gridを使用してMasonryレイアウトを作ります。
grid配下のdivの2nの要素は、md:row-end-[span_2]を使用して、2行分の高さを持たせます。
grid配下のdivの3nの要素は、md:row-end-[span_3]を使用して、3行分の高さを持たせます。
grid配下のdivの4nの要素は、md:row-end-[span_3]を使用して、3行分の高さを持たせます。
こうすることで、Pinterest風のレイアウトを作ることができます。
<div class="grid gap-6 p-4 md:auto-rows-[240px] md:grid-cols-[repeat(_auto-fill,_minmax(_300px,_1fr_)_)]">
<div class="h-auto w-full overflow-hidden rounded-[10px] bg-slate-400/40 transition-all duration-500 [box-shadow:0px_4px_8px_rgba(0,_0,_0,_0.1)] has-[.loaded]:bg-transparent md:[&:nth-child(2n)]:row-end-[span_2] md:[&:nth-child(3n)]:row-end-[span_3] md:[&:nth-child(4n)]:row-end-[span_3]">
<img
class="js-load-image h-full w-full object-cover"
src="画像パス"
alt="image"
/>
</div>
<div class="h-auto w-full overflow-hidden rounded-[10px] bg-slate-400/40 transition-all duration-500 [box-shadow:0px_4px_8px_rgba(0,_0,_0,_0.1)] has-[.loaded]:bg-transparent md:[&:nth-child(2n)]:row-end-[span_2] md:[&:nth-child(3n)]:row-end-[span_3] md:[&:nth-child(4n)]:row-end-[span_3]">
<img
class="js-load-image h-full w-full object-cover"
src="画像パス"
alt="image"
/>
</div>
<div class="h-auto w-full overflow-hidden rounded-[10px] bg-slate-400/40 transition-all duration-500 [box-shadow:0px_4px_8px_rgba(0,_0,_0,_0.1)] has-[.loaded]:bg-transparent md:[&:nth-child(2n)]:row-end-[span_2] md:[&:nth-child(3n)]:row-end-[span_3] md:[&:nth-child(4n)]:row-end-[span_3]">
<img
class="js-load-image h-full w-full object-cover"
src="画像パス"
alt="image"
/>
</div>
<!-- 省略~~~~ -->
</div>
こちらは参考程度になりますが、画像の遅延読み込みを行うために、imagesLoadedを使用します。(無くても問題ありません)
インストールは以下のコマンドで行います。
npm i -D imagesloaded
参考
imagesloaded
JavaScript is all like _You images done yet or what?_. Latest version: 5.0.0, last published: 3 years ago. Start using imagesloaded in your project by running `npm i imagesloaded`. There are 244 other projects in the npm registry using imagesloaded.
「imagesLoaded」を使って画像の読み込みを検知する|notes by SHARESL
画像の読み込みを検知する軽量なJavaScriptライブラリ「imagesLoaded」の使い方を紹介しています。実際に画像を読み込んで実行する簡単なDEMOを作ってみました。複雑な処理は必要なしでIEでも使えるのでおすすめです。
/* JavaScript */
import imagesLoaded from "imagesloaded";
const images = document.querySelectorAll("js-load-image");
/* 各画像の遅延読み込みを実行 */
images.forEach((image) => {
/* 画像が読み込まれたら、実際のソースを設定し、loaded クラスを追加 */
imagesLoaded(image, () => {
image.classList.add("loaded");
});
});
デモ