Home » Tutorials » HTML & CSS » Build Responsive Image Gallery Using CSS Calc()

Build Responsive Image Gallery Using CSS Calc()

Build Responsive Image Gallery Using CSS Calc()

In this tutorial, we will learn to leverage CSS Calc() function to fit 3 images relatively in a row with 10 pixels margin between them.

Tutorial Details

  • Difficulty: Beginner
  • Technology: CSS Calc()
  • Minimum Supported Browser: IE 11, Edge, Firefox, Chrome, Safari, iOS 8.4, Chrome for Android & Android 50

Brief introduction about CSS Calc()

Dynamically counting dimension in a responsive website is a very hard issue for web developer. Well thanks to the CSS calc(), which allows us to calculate a length value using arithmetic expression.

In this tutorial, we will try to fix the following responsive image gallery by using CSS Calc(), lets take a look on the before & after:

Before:
Before apply CSS Calc()
*The image gallery doesn’t work in responsive layout, & it is really hard for web developers to apply 10 pixels margin between the images in each row in a responsive layout.

After:
After apply CSS Calc()
*10 pixels margin has been added between each row’s images; And CSS Calc() will take cares for us when the image gallery being viewed in a responsive layout.

The Solution

We can easily solve the issue in only 2 steps:

Step 1: Adding Margin

  .row {
  	margin: 10px 0;
  	overflow: hidden;
  }

  .row img {
  	float: left;
  	margin-right: 10px;
  }

  .row img:last-of-type {
  	margin: 0;
  }

Adding margin-right to each image in a row; and remove the margin-right for the last image in the row.

Step 2: Transforming image size to responsive

  .row {
  	margin: 10px 0;
  	overflow: hidden;
  }

  .row img {
  	float: left;
  	margin-right: 10px;
  	width: calc((100% - 20px) / 3);
  }

  .row img:last-of-type {
  	margin: 0;
  }

As you seen above, we’re using CSS Calc() function in the image’s width property. We want the image gallery works in responsive layout, so we set their width to 100%.

Let’s break it down, we have added 10 pixels margin to the 1st and 2nd images, so we use 100% to minus the 20 pixels (the total margin included 1st & 2nd images), & divide it into 3.

Formula as below:
Formula to build responsive image gallery with CSS Calc()

Note: There MUST be a space on each side of the + & – operators within the CSS Calc(). For example, calc(100px – 10%) will work; While, calc(100px-10%) will NOT.

Save your document, preview it in your browser. Resize your browser & see how it works!

View Demo

Conclusion

You’ve just learn to make a responsive image gallery using CSS Calc() function in just only 2 steps! The CSS calc() is another example of CSS taking over the role of JavaScript. It’s extremely useful when you are working on responsive layout.

If you would like to learn to build an intelligent responsive layout using CSS Calc(), please read “Build Intelligent Layout Using CSS Calc() Property“.


Android, iOS Development Tutorials