A better alignment for sprite icons
You may have seen this technique before to horizontally & vertically align an icon...
.icon {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background: #000;
margin-left: -50px;
margin-top: -50px;
}
This technique is okay, but it uses two too many properties that rely on the width and height (i.e. the negative margins). This can actually be avoided by switching the way you go about it...
.icon {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
width: 20px;
height: 20px;
background: #000;
}
This is a much cleaner option, that will allow you to abstract the first 3 lines for all centred icons. It works by stretching out to the edges, then, as long as there's an explicit width and height, it will utilise the auto margin to centre the actual contents.
Check out this example if you like: http://codepen.io/joecritch/full/FwftG
Written by Joe Critchley
Related protips
1 Response
Only change the numbers at one place. Great tip.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Css
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#