Make avatars easy to customize
Sometimes avatars are a bit annoying to stylize. This is an approach Iβm trying recently, with interesting results.
The final result: http://codepen.io/nobilelucifero/full/DFprq
In my opinion, a respectable avatar should have at least two qualities:
- Be always in square proportions
- 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!