search
HomeWeb Front-endCSS TutorialAdaptive Photo Layout with Flexbox

Use Flexbox to achieve adaptive photo layout, lightweight and efficient! This article introduces a lightweight approach to creating horizontal waterfall streaming photo layouts using Flexbox, enabling seamless arrangement of photos of any size without JavaScript.

Adaptive Photo Layout with Flexbox

This solution is not only lightweight, but also very simple. We only need an unordered image list and 17 lines of CSS code, and the core lies in the Flexbox and object-fit properties.

Why choose this method?

I have two hobbies: recording life with photos, and exploring interesting ways to combine CSS attributes (both new and old).

A few weeks ago, I attended the XOXO event, took a lot of photos, and finally filtered out 39 beautiful photos. To better manage my content, I have been trying to create a simple photo blog for the past few years, but I have never been able to achieve my ideal layout: a simple waterfall layout where photos fill lines while maintaining their aspect ratio (think Photos apps on iOS, Google Photos, Flickr…).

I did some research to see if there are any lightweight, non-JavaScript options, but couldn't find any solution that matched my needs. While waiting for flight delays, I started trying some code and restrict myself from keeping the code as concise as possible (because that's exactly what I think is the fun).

Basic HTML structure

Since I'm basically creating a list of images, I chose an unordered list:


    <li>Adaptive Photo Layout with Flexbox <li>Adaptive Photo Layout with Flexbox <!-- ... more images ... -->

The wonderful uses of Flexbox

Then there are a series of moments of inspiration:

    <li> Flexbox is ideal for filling rows by determining the cell width based on the content of the cell. <li> This means that all images (land or portrait) need to have the same height. <li> I can use object-fit: cover; to make sure the image fills the cells.

In theory, this sounds like a reliable solution, and it gives me a result that I'm 90% satisfied with.

 ul {
  display: flex;
  flex-wrap: wrap;
}

li {
  height: 40vh;
  flex-grow: 1;
}

img {
  max-height: 100%;
  min-width: 100%;
  object-fit: cover;
  vertical-align: bottom;
}

Note: 40vh seems to be the best initial approach for desktop browsers, showing two lines of full photos at reasonable size and suggesting that there are more photos below. This also allows more photos to be displayed per line, which significantly improves aspect ratio.

Handle the last line of stretching issues

The only problem I've had is that Flexbox really wants to fill all the rows, and it does something weird about the aspect ratio of the last row of photos. This is probably my least favorite with this layout, but I had to add an empty one at the end of the list<li> element.

 <!-- ... more images ... -->
<li>

Combined with the following CSS code:

 li:last-child {
  flex-grow: 10;
}

Note: There is no scientific basis for using "10" here. This provides the best results in all my tests.

Demo (demo link or code snippet should be inserted here)

Viewport optimization

Some factors need to be considered when working in different viewport directions.

Vertical screen

If your viewport height is greater than width, this method limits the number of photos per row, affecting its aspect ratio. To solve this problem, you can use simple media queries to make the photo line shorter:

 @media (max-aspect-ratio: 1/1) {
  li {
    height: 30vh;
  }
}

Shorter screen

To adapt to small horizontal devices, increasing the height of the photo can help to display the photo as large as possible:

 @media (max-height: 480px) {
  li {
    height: 80vh;
  }
}

Smaller vertical screen

Most phones are not wide enough to get Flexbox to work properly without shrinking photos, so I chose not to try to hold multiple photos per line. Still, setting the maximum height here is worth it so you can at least get a glimpse of the next photo on the list.

 @media (max-aspect-ratio: 1/1) and (max-width: 480px) {
  ul {
    flex-direction: column; /* Change to column direction*/
  }

  li {
    height: auto;
    width: 100%;
  }

  img {
    width: 100%;
    max-height: 75vh;
    min-width: 0;
  }
}

Summarize

This approach doesn't completely respect the aspect ratio of the photo (but is already close) and occasionally leads to some weird results, but I absolutely love its simplicity and flexibility. Want to get your gallery to scroll horizontally instead of vertically? Just make some adjustments. Is there 1,000 photos in the gallery or only one? All look good. Not sure about aspect ratio? Flexbox is your best choice. If you haven't viewed the demo yet, please read it again and let me know what you think!

Additional Tips

Depending on the size of these photos, such pages may grow to several megabytes very quickly. In my blog, I added loading="lazy" to solve this problem. With this property, images will only load when you are close to them as you scroll. Currently it is only supported in Chrome, but you can write a more widely supported technology yourself.

The above is the detailed content of Adaptive Photo Layout with Flexbox. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Where should 'Subscribe to Podcast' link to?Where should 'Subscribe to Podcast' link to?Apr 16, 2025 pm 12:04 PM

For a while, iTunes was the big dog in podcasting, so if you linked "Subscribe to Podcast" to like:

Browser Engine DiversityBrowser Engine DiversityApr 16, 2025 pm 12:02 PM

We lost Opera when they went Chrome in 2013. Same deal with Edge when it also went Chrome earlier this year. Mike Taylor called these changes a "Decreasingly

UX Considerations for Web SharingUX Considerations for Web SharingApr 16, 2025 am 11:59 AM

From trashy clickbait sites to the most august of publications, share buttons have long been ubiquitous across the web. And yet it is arguable that these

Weekly Platform News: Apple Deploys Web Components, Progressive HTML Rendering, Self-Hosting Critical ResourcesWeekly Platform News: Apple Deploys Web Components, Progressive HTML Rendering, Self-Hosting Critical ResourcesApr 16, 2025 am 11:55 AM

In this week's roundup, Apple gets into web components, how Instagram is insta-loading scripts, and some food for thought for self-hosting critical resources.

Git Pathspecs and How to Use ThemGit Pathspecs and How to Use ThemApr 16, 2025 am 11:53 AM

When I was looking through the documentation of git commands, I noticed that many of them had an option for . I initially thought that this was just a

A Color Picker for Product ImagesA Color Picker for Product ImagesApr 16, 2025 am 11:49 AM

Sounds kind of like a hard problem doesn't it? We often don't have product shots in thousands of colors, such that we can flip out the with . Nor do we

A Dark Mode Toggle with React and ThemeProviderA Dark Mode Toggle with React and ThemeProviderApr 16, 2025 am 11:46 AM

I like when websites have a dark mode option. Dark mode makes web pages easier for me to read and helps my eyes feel more relaxed. Many websites, including

Some Hands-On with the HTML Dialog ElementSome Hands-On with the HTML Dialog ElementApr 16, 2025 am 11:33 AM

This is me looking at the HTML element for the first time. I've been aware of it for a while, but haven't taken it for a spin yet. It has some pretty cool and

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft