Arms crossed picture of James Auble
bootstrap 3

Make Image Fill Column Height with Bootstrap 3

PublishedJun 1st, 2019

This past week I jumped into an existing project using Bootstrap 3. As I’m relatively green to web development, I had started using Bootstrap after Bootstrap 4 alpha was released and so always had used Bootstrap grids using flexbox under the hood.

When I went to add a background image to an empty column, I found that the image didn’t fill up the column height as I was used to with Bootstrap 4.

After fighting with many different properties trying to get the image to fill up its parent’s height, I reached out to a coworker who gave me a quick fix to get it to show.

If your markup looks something like this:

<div class="container">
 <div class="row custom-class">
  <div class="col-md-6">
   <img src="image/path.jpg" alt="">
  </div>
  <div class="col-md-6">
   Some Content...
  </div>
 </div>
</div>

Then you can get the image to fill its parent by setting your row element to flex:

.custom-class {
  display: flex;
}

Easy fix if you know what to do. But what is the reason for this?

The answer lies in the align-items property of the Flexible Box Layout Module. By default, your flex container will treat children elements of the container as flex items with flex-direction defaulting to row.

They are now lined up on the “inline axis” or as a row.

We can really thank the align-items for expanding our image though. Once you applied display: flex to the container, the defaultalign-items: stretch was applied to the image’s container and now your image has a viewport the size of your row and can be seen.

BONUS TIP: Positioning your image within its container without using object-position.

Our CSS for the image and its parent will look like this:

.img__container {
  position: relative;
  overflow: hidden;
}
.img__container img {
  position: absolute;
  min-height: 100%;
  min-width: 100%;
  width: 0;
}

First, we set our image’s parent to position: relative; so that our image has something to position to.

Also, we’ll add overflow: hidden so that no matter the size of our image or the positioning, it can only be as big as its parent.

This next part is the part I really like, first we set position: absolute so that we can easily play with its position, nothing depends on its location so we don’t have to work about taking it out of the document flow.

Next we want it to act like background-size: cover so we always want it to fill the viewport.

We set min-height: 100%; and min-width: 100% so that the image will set its smallest side to the size of the parent. But wait, the image still wants to be as big as it intrinsically is. The way we size it down is to set width: 0 so it tries to shrink as small as it can, which is the size of its parent.

Thought this was a fun trick! Hope you enjoyed it!

Happy dev’ing.

Need a web developer?

Contact Me
Back to Blog
Scrolldown Icon