Make avatars easy to customize

Sometimes avatars are a bit annoying to stylize. This is an approach I’m trying recently, with interesting results.

Fancy avatars!

The final result: http://codepen.io/nobilelucifero/full/DFprq

A small crop of the final result.

In my opinion, a respectable avatar should have at least two qualities:

  1. Be always in square proportions
  2. Be easily customizable

For each quality I had to pick up a certain technique and make it work well.

1. Keeping it square

About the avatar’s image: I won’t do any particular magic here. Just avoiding it overflows vertically or horizontally its container.

A long time ago, I’ve read a tutorial on how to keep 16:9 or 4:3 proportions for videos using a simple pseudo-element styling (if you remember it, tell me please!).
So I wondered: why not apply 1:1 proportions, a square form factor?.

I know it’s possible to achieve a basically identical result without a pseudo-element, moving the code in the container itself.
But then, the interested container has to be always set to display: block in order to make it work (which is better for grids) and basically always you might prefer to have such elements set to display: inline-block (like avatars next to the username).

The final code looks like this:

.avatar {
position: relative;
overflow: hidden;
width: 100%;
}
/* keep square proportions */
.avatar:before {
content: β€œβ€;
display: block;
position: relative;
padding-bottom: 100%;
}
/* style for the inner avatar image */
.avatar--media {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: auto;
}

The trick basically works because padding inherits the size of width, as specified by the W3C. Nice to know, right?

2. Make it customizable

I see sometimes some fancy ways to add graphical effects to avatars. Usually they have surrounding div(s) or some image mask. I think it’s a pity, given the power of CSS nowadays.
To solve the question, I pick up the pseudo-element left from my avatar, in order to create an upper mask, with some inherited styles like sizes and border radius to avoid repeated rules.

/* upper customizable mask */
.avatar:after {
content: β€œβ€;
position: absolute;
top: 0;
left: 0;
width: inherit;
height: 100%;
border-radius: inherit;
}

I tested this on Chrome, Firefox, IE and Safari. Only the last one has some kind of jagged rendering, but I’m trying to understand the reasons behind this odd effect.

So yes, this is everything for now I guess. I hope this tip was useful or at least interesting!

The final result: http://codepen.io/nobilelucifero/full/DFprq

Final comment

Would you like to see other posts like this? Have you find what I wrote interesting so far? Do you think I should change something immediately? Let me know what feedbacks you have for me. Thanks a lot!

--

--