How to Add Space Between Images in CSS?

There are several easy ways to add space between images using CSS.

However, the simplest approach is to use the margin property. The margin property lets us create a space around the HTML elements.

The margin property is actually a shorthand of the margin-top, margin-right, margin-bottom, and margin-left properties. You can either use the margin or its shorthand properties to add space between the images.

For the horizontal spacing, you can use the margin-left and margin-right. While for the vertical spacing you can use the margin-top and margin-bottom properties.

The space value can be specified in any CSS units such as px, cm, em, rem, etc.

In the following example, we have specified a 30px horizontal space using the margin-right property and 30px vertical space using the margin-bottom property.

Example:

img{
   width: 150px;
   height: 150px;
   margin-right: 30px;   /* Horizontal Space */
   margin-bottom: 30px;  /* Vertical Space */
   border: 2px solid red;
}

We can also achieve the same spacing using the margin-left and margin-top properties. But it will create a 30px unnecessary space on top of the first row of images and also a 30px space left to the first column of the images.

This is the reason we choose the margin-right and margin-bottom properties in the above example. However, I am not saying that you should not use the margin-left and margin-top properties. You can use any of the four properties whichever is needed.

Here is the same example as above but with the margin-left and margin-top properties with a value of 30px.

Example:

img{
   width: 150px;
   height: 150px;
   margin-left: 30px;   /* Horizontal Space */
   margin-top: 30px;  /* Vertical Space */
   border: 2px solid red;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.