1

I wanted to make a grid of images using css grid, with all images being different sized squares.

I stumbled on the article on css tricks: Aspect Ratios for Grid Items

On their example on codepen I noticed that the square 1/1 ratio grid is always 4px higher than wide.

I can't figure out how to remove these 4px.

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  place-items: start;
}
.grid > * {
  background: orange;
  width: 100%;
}
.grid > [style^='--aspect-ratio']::before {
  content: "";
  display: inline-block;
  width: 1px;
  height: 0;
  padding-bottom: calc(100% / (var(--aspect-ratio)));
  vertical-align: bottom; /* new */
}
<div class="grid">
  <div style="--aspect-ratio: 2/1;">2/1</div>
  <div style="--aspect-ratio: 3/1;">3/1</div>
  <div style="--aspect-ratio: 1/1;">1/1</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Timar Ivo Batis
  • 1,861
  • 17
  • 21
  • 1
    The `::before` pseudo-element is set to `display: inline-block`. This activates baseline alignment, which breaks the 1:1 ratio. Add `vertical-align: bottom` to the pseudo-element. – Michael Benjamin Aug 13 '19 at 23:54

0 Answers0