How To Align Images Side By Side In Css

In this article, I’m going to show you how to align images side by side in CSS. As a web developer, I often come across situations where I need to place multiple images next to each other. Whether it’s showcasing a gallery of pictures or displaying before-and-after images, aligning images side by side is a common requirement.

Before we dive into the code, let’s briefly discuss why CSS is the best choice for aligning images. CSS, short for Cascading Style Sheets, is a powerful styling language that allows us to control the appearance and layout of elements on a webpage. With CSS, we can easily manipulate the positioning and size of images, making it the perfect tool for aligning images side by side.

Step 1: HTML Markup

The first step is to create the HTML markup for our images. Let’s assume we have three images that we want to align side by side:


<div class="image-container">
  <img src="image1.jpg" alt="Image 1">
  <img src="image2.jpg" alt="Image 2">
  <img src="image3.jpg" alt="Image 3">
</div>

As you can see, we have wrapped the images in a <div> element with a class of “image-container”. This will allow us to target and style the container later in our CSS.

Step 2: CSS Styling

Next, let’s move on to the CSS part. We’ll use CSS flexbox to align the images side by side:


.image-container {
  display: flex;
}

.image-container img {
  flex: 1;
  margin: 10px;
}

In the CSS code above, we first set the display property of the .image-container to flex. This allows the images to be arranged in a row. Then, we add some margin to give space between the images. The flex: 1 property ensures that each image takes up an equal amount of space.

Feel free to experiment with the margin value to adjust the spacing between images according to your preference.

Step 3: Personal Touches

Now that we have aligned the images side by side, let’s add some personal touches to make the gallery look more appealing. We can apply a border and a hover effect to the images:


.image-container img {
  border: 1px solid #ddd;
  border-radius: 5px;
}

.image-container img:hover {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

The CSS code above adds a border with rounded corners to each image using the border and border-radius properties. When you hover over an image, it will have a subtle box-shadow effect applied to it, giving it a more interactive feel.

Conclusion

Aligning images side by side in CSS is a straightforward process, thanks to the flexbox layout module. By using the display: flex property and some additional styles, we can easily create a visually appealing gallery of images.

Remember to experiment with different CSS properties and values to achieve the desired layout and aesthetics for your images. With CSS, the possibilities are almost endless!