adiaz.uy (@HiroAgustin)

User Avatar

If your app has users, I bet they have avatars. Rounded avatars are pretty much a standard on any UI, so you might be inclined to code something like this:

User avatar placeholder

<img
  class="Avatar"
  src="https://placekitten.com/200/200"
  alt="User avatar"
>
.Avatar {
  height: 100px;
  border-radius: 50%;
  width: 100px;
}

Done, right? Push that commit, merge it to master, deploy it to prod, and go grab that well earned chocolate chip cookie.

What about non-square images?

Fuck.

User avatar placeholder User avatar placeholder

You could add one of those modals where the user edits their own avatar and store a cropped version of the image; I much rather use some CSS magic:

<picture class="Avatar">
  <img
    src="https://placekitten.com/200/200"
    alt="User avatar"
  >
</picture>
.Avatar {
  border-radius: 50%;
  height: 100px;
  overflow: hidden;
  width: 100px;
}

.Avatar > img {
  height: 100%;
  object-fit: cover;
  width: 100%;
}

User avatar placeholder User avatar placeholder User avatar placeholder

Using object-fit: cover on the img element makes it fit nicely inside its container, and we use overflow: hidden literally to cut corners. All achieved without the use of annoying modals or pesky JS. Now go get that cookie.

Bonus tip: use CSS Variables to create modifiers for the different types and sizes of avatars you’ll need:

.Avatar {
  --avatar-size: 100px;
  --avatar-radius: 50%;

  border-radius: var(--avatar-radius);
  height: var(--avatar-size);
  overflow: hidden;
  width: var(--avatar-size);
}

.Avatar--square { --avatar-radius: 8px; }
.Avatar--small { --avatar-size: 50px; }
.Avatar--large { --avatar-size: 150px; }

User avatar placeholder User avatar placeholder User avatar placeholder