ML.
← Posts

Maintaining image aspect ratio with CSS

react-hook-form

SeongHwa Lee··1 min read

Background

One of the most important tasks when building an e-commerce site is laying out product thumbnail images. Typically, thumbnails are displayed at a 1:1 ratio or some other specific ratio that reflects the store's concept. Despite having implemented this many times, I always felt the approach was less than elegant.

Previous approaches

Using margin-top

<div class='item'>
  <div class='dummy'></div>
  <div class='title'></title>
</div>
.item {
  position: relative;
}
.dummy {
  margin-top: 100%;
}
.title {
}

aspect ratio

<div class="demo"></div>
.demo {
  background: black;
  width: 500px;
  aspect-ratio: 4/3;
}

This sets the element's width-to-height ratio to 4:3. Amazing.

Examples

Usage

References

stackoverflow