Chris Spittles Chris Spittles - 7 months ago 18
HTML Question

Match button height based on image aspect ratio

I have a group of 16x9 images that are set to a percentage width (20%) with an add button thrown into the mix. I need the height of the add button to equal that of the images. I've tried setting the "height" of the button using

padding-top
and I've set it to 11.25% which is 9/16 of 20%.

This almost works in Chrome but in the example, when you resize the window (in fullscreen), sub-pixel rendering kicks in and renders a height greater for the button than the image resulting in wrapping issues.

Is there a better way of achieving this using flexbox perhaps? one that will work without sub-pixel rendering issues?



.imageSection {
box-sizing: border-box;
overflow: hidden;
}

.imageSection > img,
.imageSection > button {
width: 20%;
float: left;
box-sizing: border-box;
}

.imageSection > button {
padding: 0;
border: 0;
margin: 0;
padding-top: 11.25%; /* (20 / 16) * 9 */
position: relative;
background: #bd2a72;
color: #fff;
}

.imageSection > button::after {
content: "+";
position: absolute;
width: 30px;
height: 14px;
top: 50%;
left: 50%;
margin-left: -15px;
margin-top: -7px;
}

<div class="imageSection">
<button></button>
<img src="http://placehold.it/1600x900" />
<img src="http://placehold.it/1600x900" />
<img src="http://placehold.it/1600x900" />
<img src="http://placehold.it/1600x900" />
<img src="http://placehold.it/1600x900" />
<img src="http://placehold.it/1600x900" />
</div>




Answer

What about this?

.imageSection {
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  align-items: stretch;
  position: relative;
  flex-wrap:wrap;
}

.imageSection > img,
.imageSection > button {
  width: 20%;  
  box-sizing: border-box; 
  height:100%;
}

.imageSection > button {
  padding: 0;
  border: 0;
  margin: 0;
  position: relative;
  background: #bd2a72;
  color: #fff;
  height:inherit;
}

.imageSection > button::after {
  content: "+";
  position: absolute;
  width: 30px;
  height: 14px;
  top: 50%;
  left: 50%;
  margin-left: -15px;
  margin-top: -7px;
}
<div class="imageSection">
  <button></button>
  <img src="http://placehold.it/1600x900" />
  <img src="http://placehold.it/1600x900" />
  <img src="http://placehold.it/1600x900" />
  <img src="http://placehold.it/1600x900" />
  <img src="http://placehold.it/1600x900" />
  <img src="http://placehold.it/1600x900" />
</div>