CODE LAB: 20 CSS code snippets to make your life easier

With so many new trends advancing every year it can be difficult keeping up with the industry. Website designers and frontend developers have been deeply ingrained into the newer CSS3 properties, determining the ultimate browser support and quirky hacks. But there are also brilliant CSS2 code snippets which have been tossed aside in comparison.

CSS Resets Basic CSS browser resets are some of the most common snippets you’ll find online.

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, 
pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, 
samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, 
fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, 
aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, 
ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
outline: none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
html { height: 101%; }
body { font-size: 62.5%; line-height: 1; font-family: Arial, Tahoma, sans-serif; }

article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; }
ol, ul { list-style: none; }

blockquote, q { quotes: none; }
blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; }
strong { font-weight: bold; }

table { border-collapse: collapse; border-spacing: 0; }
img { border: 0; max-width: 100%; }

p { font-size: 1.2em; line-height: 1.0em; color: #333; }

Cross-Browser Transparency Some of the newer CSS3 properties have pampered us into thinking they may be applied everywhere. Unfortunately opacity is one such example where CSS still requires some minor updates. Appending the filter property should handle any older versions of IE with grace.

.transparent {
filter: alpha(opacity=50); /* internet explorer */
-khtml-opacity: 0.5;      /* khtml, old safari */
-moz-opacity: 0.5;       /* mozilla, netscape */
opacity: 0.5;           /* fx, safari, opera */

General Media Queries This is an excellent template which you can find on CSS-Tricks for other bits and pieces of media queries. However I’ve copied their example in full which includes tons of real mobile devices. These codes will even target retina-based devices using min-device-pixel-ratio.

/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */

/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
/* Styles */

/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
/* Styles */

/* iPhone 4 ----------- */
@media only screen and (-webkit-min-device-pixel-ratio:1.5), only screen and (min-device-pixel-ratio:1.5) {
/* Styles */

Hiding H1 Text for Logo I first noticed this technique being implemented on the old Digg layout. You can setup an H1 tag which also has your website’s name in plaintext for SEO purposes. But using CSS we can move this text so it isn’t visible, and replace it with a custom logo image.

h1 {
text-indent: -9999px;
margin: 0 auto;
width: 320px;
height: 85px;
background: transparent url("images/logo.png") no-repeat scroll;

Polaroid Image Border Applying this basic snippet will allow you to implement .polaroid classes onto your images. This will create the old photo-style effect with a large white border and some slight box shadows. You’ll want to update the width/height values to match that of your image dimensions and website layout.

img.polaroid {
background:#000; /*Change this to a background image or remove*/
border:solid #fff;
border-width:6px 6px 20px 6px;
box-shadow:1px 1px 5px #333; /* Standard blur at 5px. Increase for more depth */
-webkit-box-shadow:1px 1px 5px #333;
-moz-box-shadow:1px 1px 5px #333;
height:200px; /*Set to height of your image or desired div*/
width:200px; /*Set to width of your image or desired div*/

Fullscreen Backgrounds with CSS3 I should note that this code will not work properly in older browsers which do not support CSS3 syntax. However if you’re looking for a quick solution and don’t care about legacy support, this is the best chunk of code you’ll find! Great for adding big photographs into the background of your website while keeping them resizable and fixed as you scroll.

html {
background: url('images/bg.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

@font-face Template Here is another bit of CSS3 code which isn’t the easiest to memorize. Using @font-face you may embed your own TTF/OTF/SVG/WOFF files into your website and generate custom font families. Use this template as a base example for your own projects in the future.

@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff') format('woff'), /* Modern Browsers */
url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */

body {
font-family: 'MyWebFont', Arial, sans-serif;

CSS3 Zebra Stripes Possibly the best item to include zebra stripes is within a table of data. It can be difficult when users are scanning 40 or 50 rows to determine exactly which cell is lined up to which row. By adding zebra stripes on default we can update odd rows with varying background colors.

tbody tr:nth-child(odd) {
background-color: #ccc;

Centered Layout Fixed Width Quick snippet for horizontal positioning, which is perfect to be used on fixed-width layouts.

#page-wrap {
width: 800px;
margin: 0 auto;

CSS Fixed Footer This is actually a lot more useful than it sounds, but appending a fixed footer into your website is quite simple. These footers will scroll with the user and may contain helpful information about your site or unique contact details. Ideally this would only be implemented in cases where it truly adds value to the user interface.

#footer {
position: fixed;
left: 0px;
bottom: 0px;
height: 30px;
width: 100%;
background: #444;

/* IE 6 */
* html #footer {
position: absolute;
top: expression((0-(footer.offsetHeight)+(document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)+(ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop))+'px');

Cross-Browser Minimum Height Developers who have needed to work with min-height know all about the shady support. Many newer browsers can handle this perfectly, however Internet Explorer and older versions of Firefox do have trouble. This set of codes should provide a fix to any related bugs.SSS

#container {
min-height: 550px;
height: auto !important;
height: 550px;

Style Links Based on Filetype Quite the obscure bit of CSS but I love the creativity! You can determine the file type of your links using CSS selectors and implement icons as background images. These may include the various protocols (HTTP, FTP, IRC, mailto) or simply the file types themselves (mp3, avi, pdf).

/* external links */
a[href^="http://"] {
padding-right: 13px;
background: url('external.gif') no-repeat center right;

/* emails */
a[href^="mailto:"] {
padding-right: 20px;
background: url('email.png') no-repeat center right;

/* pdfs */
a[href$=".pdf"] {
padding-right: 18px;
background: url('acrobat.png') no-repeat center right;

Force Hand Cursor over Clickable Items There are lots of default clickable HTML elements which do not always display the hand pointer icon. Using this set of CSS selectors you may force the pointer over a number of key elements, along with any other objects using the class .pointer.

a[href], input[type='submit'], input[type='image'], label[for], select, button, .pointer {
cursor: pointer;

Default H1-H5 Headers This template includes default styles for all major heading elements ranging from H1-H5. You may also consider adding H6 but I have never seen a website using all six nested headers.

color: #005a9c;
font-size: 2.6em;
line-height: 2.45em;
font-size: 2.1em;
line-height: 1.9em;
font-size: 1.8em;
line-height: 1.65em;
font-size: 1.65em;
line-height: 1.4em;
font-size: 1.4em;
line-height: 1.25em;

Dark Grey Rounded Buttons As another helpful template for web developers I have included this simplistic CSS3 buttons class. I am using the class name .graybtn which is appropriate for the colors, but this isn’t to say you couldn’t change the styles to match your own website. Check out the hex values inside a color wheel to match similar hues in different color ranges.

.graybtn {
-moz-box-shadow:inset 0px 1px 0px 0px #ffffff;
-webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;
box-shadow:inset 0px 1px 0px 0px #ffffff;
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #d1d1d1) );
background:-moz-linear-gradient( center top, #ffffff 5%, #d1d1d1 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#d1d1d1');
border:1px solid #dcdcdc;
padding:6px 24px;
text-shadow:1px 1px 0px #ffffff;
.graybtn:hover {
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #d1d1d1), color-stop(1, #ffffff) );
background:-moz-linear-gradient( center top, #d1d1d1 5%, #ffffff 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#d1d1d1', endColorstr='#ffffff');
.graybtn:active {

Condensed CSS Font Properties The main reason web developers don’t always use this condensed font property is because not every setting is needed. But having an understanding of this shorthand may save you a lot of time and space in your stylesheets. Keep this snippet handy just in case you ever want to shorten the formatting of your font styles.

p {
font: italic small-caps bold 1.2em/1.0em Arial, Tahoma, Helvetica;

Use Flexbox For Layouts The flexbox model exists for a reason. Floats and inline-blocks work, but they are all essentially tools for styling documents, not websites. Flexbox on the other hand is specifically designed to make it easy to create any layout exactly the way it was envisioned.

The set of properties that come with the flexbox model give developers lots of flexibility (no pun intended), and once you get used to them, doing any responsive layout is a piece of cake. Browser support nowadays is almost perfect, so there shouldn't be anything stopping you from going full flexbox.

.container {
display: flex;
/* Don't forget to add prefixes for Safari */
display: -webkit-flex;

Write Better Comments CSS might not be a programming language but it's code still needs to be documented. Some simple comments are all it takes to organize a style sheet and make it more accessible to your colleagues or your future self.

For larger sections of the CSS such as major components or media-queries, use a stylized comment and leave a couple of new lines after:

header { }

header nav { }

.slideshow { }

CSS Animations with transform Don't animate elements by directly changing their width and height, or left/top/bottom/right. It's preferred to use the transform() property as it provides smoother transitions and makes your intentions easier to understand when reading the code.

Here's an example. We want to animate a ball and slide it out to the right. Instead of changing the value of left, it's better to use translateX():

.ball {
left: 50px;
transition: 0.4s ease-out;

/* Not Cool*/
.ball.slide-out {
left: 500px;

/* Cool*/
.ball.slide-out {
transform: translateX(450px);

Em, Rem, and Pixel There is a lot of debate whether people should use em, rem, or px values for setting the size of elements and text. Truth is, all three options are viable and have their pros and cons.

All developers and projects are different, so there can't be any strict rules on when to use which. Here are, however, some tips and general good practices for each unit:

  • em - The value of 1 em is relative to the font-size of the direct parent. Often used in media-queries, em is great for responsiveness, but it can get really confusing tracing back the exchange rate of ems to pixels for each element (1.25em of 1.4em of 16px = ?).
  • rem - Relative to the font-size of the html element, rem makes it really easy to scale all headings and paragraphs on the page. Leaving the html with it's default fontsize and setting everything else with rem is a great approach accessibility-wise.
  • px - Pixels give you the most precision but don't offer any scaling when used in responsive designs. They are reliable, easy to understand, and present a good visual connection between value and actual result (15px is close, maybe just a pixel or two more). Bottom line is, don't be afraid to experiment, try them all and see what you like best. Sometimes em and rem can save you a lot of work, especially when building responsive pages.

* Disclaimer. Since free code is available out there on the internet, and so many people have written up about the use of it I decided to use some examples from a source I trust. And in this line I would like to thank them and everyone else that shares there code, for this and reference them in this regard.