How to Align Images Side by Side With CSS

Aligning images side by side is a common requirement in web design and front-end development.

This can be achieved using CSS, which stands for Cascading Style Sheets.

In this tutorial, we will explore different ways to align images side by side using CSS and provide code examples to help you get started.


Method 1: Using the Float Property

The float property is used to specify how an element should float within its parent container.

When two or more images are assigned the float property, they will automatically align side by side.

Here’s an example of how to use the float property in CSS:

HTML:

<div class="container">
  <img src="image1.jpg" class="img1" />
  <img src="image2.jpg" class="img2" />
</div>

CSS:

.container {
  overflow: hidden;
}

.img1 {
  float: left;
}

.img2 {
  float: right;
}

Method 2: Using the Flexbox Layout

Flexbox is a modern CSS layout technique that makes it easy to align elements in a flexible and responsive way.

To align images side by side using flexbox, you need to set the display property of the parent container to flex and specify the align-items property as center.

Here’s an example of how to use flexbox in CSS:

HTML:

<div class="container">
  <img src="image1.jpg" class="img1" />
  <img src="image2.jpg" class="img2" />
</div>

CSS:

.container {
  display: flex;
  align-items: center;
}

.img1 {
  flex: 1;
}

.img2 {
  flex: 1;
}

Method 3: Using the Grid Layout

Grid is another modern CSS layout technique that allows you to create a grid of elements, including images.

To align images side by side using grid, you need to set the display property of the parent container to grid and specify the grid-template-columns property as equal.

Here’s an example of how to use grid in CSS:

HTML:

<div class="container">
  <img src="image1.jpg" class="img1" />
  <img src="image2.jpg" class="img2" />
</div>

CSS:

.container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.img1 {
  grid-column: 1;
}

.img2 {
  grid-column: 2;
}

Conclusion:

Aligning images side by side is a common requirement in web design and front-end development.

In this article, we have explored three methods to align images side by side using CSS, including the float property, flexbox, and grid.

We have provided code examples to help you get started with each method.

By understanding these different techniques, you can choose the one that best fits your needs and create beautiful, responsive web designs.