Flexbox with Images: Use a Wrapper Element Around Your Images

Make sure to use a wrapper element around your images

Wesley (ByteGrad)'s photo
Wesley (ByteGrad)
·Nov 10, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

You need to master both Flexbox and CSS Grid in order to professionally build modern websites & web apps. If you haven't mastered both of them yet, I highly recommend going through my CSS Course.

Group 20.png

When you use Flexbox with a lot of images, like a gallery component, you might want to consider wrapping each image in a div-element. This solves a lot of issues with images in Flexbox.

So you get this structure:

<div class="gallery">
  <div class="gallery__item>
    <img class="gallery__img">
  </div>
  <div class="gallery__item>
    <img class="gallery__img">
  </div>
  <div class="gallery__item>
    <img class="gallery__img">
  </div>
  <div class="gallery__item>
    <img class="gallery__img">
  </div>
</div>
.gallery {
  display: flex;
}

.gallery__item {

}

.gallery__img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* best practice for sizing images in CSS -- to prevent distorted look for images */
}

Note that now you can't use the Flexbox functionalities on the image elements, because they are not the flex-items (their wrapper-elements are).

By the way, I think CSS is the 'bottleneck' to most websites & web apps. I believe it's the highest-ROI skill you can master.

Before I mastered CSS, I lost a ton of time & energy fiddling around with CSS.

I was learning about advanced JavaScript topics when I couldn't even implement basic layouts in CSS...

So I created a CSS course to help you avoid the same mistake. Check it out here if you're interested.

Would you like to be notified when I release a new course? You'll get early bird discounts. Sign up for my newsletter here.

Also, I show projects of upcoming courses on social media, follow me here:

Facebook Twitter Instagram

 
Share this