How to make an image equal width and height with CSS?

Nattapon Jaroenchai
2 min readSep 9, 2021

--

Today, I am working on a web template for my lab’s new project. I have a problem when was working on a people page. I want to make people's photos responsive with qual width and height. And their image has to be centered.

My expected result

Centered image with equal width and height.

The solution

HTML:

<div class=”col-6 col-sm-4 col-md-2 col-lg-2">
<div class=”card people-card “>
<div class=”card-img-top box-shadow” style=”background-image: url(‘https://www.shoppingcentreawards.com/wp-content/uploads/2015/06/people-img7.jpg');"></div>
<div class=”card-body “>
<h5 class=”card-title name “>John Smith</h5>
<p class=”card-text position “>Professor</p>
<p class=”card-text affiliation “>Department of Geography, UIUC</p>
</div>
</div>
</div>

SCSS

.people-card .card-img-top {
display: inline-block;
padding-bottom: 100%;
width: 100%;

background-position: center;
background-size: cover;
background-repeat: no-repeat;
border: 1px solid #E5E5E5;
border-radius: 50%;
-webkit-transition: all .2s;
transition: all .2s;
}

This solution works because we take the advantage of padding and background-image attributes. Even though the actual “card-img-top” element height is zero, it is extended by padding 100% which is equal to the width 100%.

Then, the image is set as the background of the element and is centered by the background-position attribute.

Result

We can just change the background-image attribute to change the images.

--

--

Nattapon Jaroenchai
Nattapon Jaroenchai

Written by Nattapon Jaroenchai

Ph.D. Student in Geography and GIS at University of Illinois at Urbana-Champaign. Part-time web developer and web designer, photographer, gamer, and etc.

No responses yet