Solution for responsive images covering entire container and keeping aspect ratio

This solution is probably already out there somewhere on the interwebs, but I write it down for now.

I’ve been working with a Bootstrap 4 based website a lot lately.
Today I got the requirement to make an background image adjust to the height of its sibling column but at the same cover the entire background of its container.

I want the entire container box to be covered by the background image and still keeping its aspect ratio in various screen sizes, it’s ok with clipping and stretching (if image is to small). Here is a solution:

html:

<div class="row">
	<div class="col-6">
		<div class="teaser-container" id="teaser1">
			...column 1 html content...
		</div>
	</div>		
	<div class="col-6">
		<div class="teaser-container" id="teaser2">
			...column 2 other various height html content...
		</div>
	</div>			
</div>

css:

#teaser1
{ 
	height: 100%; 
	background-image: url('/globalassets/top-image.jpg');
	background-repeat: no-repeat;
	background-position: center;
	background-size: cover;
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *