0

I'm able to make a square div element. But the same styles applied to an img tag create a collapsed element- not a square.

.square{
  width:20%; 
  border: 3px solid red;
}
.square:after{
  content: "";
  display: block;
  padding-bottom: 100%;
}
img:<br>
<img class='square'/>
<br>
div:<br>
<div class='square'></div>

It seems this is because img tags are replaced elements and :before and :after only work with non-replaced elements. source

But I want the img element to stay square even if the image source doesn't load. So how can I make a square empty img?

Dashiell Rose Bark-Huss
  • 2,173
  • 3
  • 28
  • 48

1 Answers1

0

I solved this by putting img in a wrapper.

.wrapper {
  display: flex;
  position: relative;
  border:3px solid red;
  width: 30%;
  overflow: hidden; /*  helpful if you make border radius 50% turning this into a circle */
}

.wrapper:after {
  content: '';
  display: block;
  padding-bottom: 100%;
}

.wrapper img {
  width: 100%;
  /* css below helps keep the wrapper square when the image src is tall and skinny */
  position: absolute;
  top: 50%;
  transform: translateY(-50%);

}
<div class="wrapper"><img src="blank.gif"/></div>
Dashiell Rose Bark-Huss
  • 2,173
  • 3
  • 28
  • 48