How to Create a Responsive Image Gallery with Flexbox

How to Create a Responsive Image Gallery with Flexbox:-Flexbox is module of CSS layout that makes creation of flexible UI. It allows easy to use alternatives to floats and some JQuery Plugins like image gallery libraries as well. Flexbox is best choice for various typical CSS tasks and fits well with one-dimensional layouts. In our today’s post we will let you know how to use flexbox to build responsive image gallery at every viewport sizes.

How to Create a Responsive Image Gallery with Flexbox

  1. Create HTML:- Let’s start with creating HTML. It’s a simple div with couple of image tags. Images are rapidly pulled and generated from Unsplash source API. In this .item class stands for flex items while .container class stands for flex container.

The browsers stack the images next to each other nicely, retaining the original 320 x 240px image size. If you resize the browser window you find that the images are not responsive which a big issue is if you use larger images. It is hard to change their position & alignment as well. Flexbox will make it easier to handle images.

  1. Add Basic Reset Styles:- To remove the default styling of browser, let’s start CSS with reset styles. We’ll use simplified version of Eric Meyer’s reset stylesheet. It includes HTML element we need for the gallery.

Also we’ll add box sizing: border-box property to whole page so paddings and borders will included in total width & height of the elements. It’s recommended to use this for flexbox otherwise paddings and borders will disappear from end of rows.

  1. Create Flexbox layout:- creating layout through flexbox is pretty simple- just a line of code. Only we need to set flex container to display: flex. We don’t need to add any CSS rules to flex items.
  2. Wrap the images:- Stacking images in the same row can be good for some layouts. For example if you have just few images. However for image galleries, image grids are used frequently. So let’s see how to fix images in neat grid.

We need to use flex-wrap property that specifies if the items are laid out in one or multiple lines. By default its value is nowrap which means all items are laid in a single line. However if we use wrap, image will nicely flow into grid. We have to use flex-wrap rule to flex container.

After page reloading you can see the images retained their original sizes and wrapped into multiple rows.

  1. Add a Gap:- Before looking into alignment, add some gap around images. Probably biggest infirmity of flexbox is that it has no gap property similar to CSS grid’s grid-gap. So we use traditional method and add some margins around flex items.
  2. Align the images:- Flexbox layout module enables you to align flex items in couple of different methods using justify-content CSS property. By default its value is flex-start that lays out flex items from initial to the end of row.