Kick-Start Your Project: A Collection of Handy CSS Snippets

Don't start your project with an empty style sheet: there are many great snippets that can make your life easier and speed up web development. We are going to show you some handy snippets that you might find useful for kick-starting your next project.

In one of the previous articles “Basic Ready-to-Use CSS Styles”, we saw how we could create a suite of classes to help the design process while making a website. I hope you made your own set of patterns!

Today we are going to see how we can continue this exercise with some things a little bit more technical. I’ll show you a bunch of CSS snippets you may or may not know, which can dramatically increase your CSS development speed.

Indeed, isn’t there some properties or CSS tricks you always have to check the syntax for, every single time you want to use them? Don’t you ever want to have some kind of way to avoid endlessly repeating the same lines of code?

Of course you do my friends! We will see how we can fix all of this. And in the meantime, we will briefly introduce some very useful mixins for those of you who are digging into CSS preprocessors. What do you say? Ready?

Shorthand classes

Let’s begin with shorthand classes, which are a very common things. The point is to allow you to quickly do this or that without struggling to target your element with crazy town selectors.

The best example is probably the one where you have some text and an image you want to include on the left side of the text. You can either target the image directly in the context (class/ID) or use one of your awesome shorthand classes:

.float-left /* Or whatever name you like */ {
float: left;
}
.float-right /* Or whatever name you like */ {
float: right;
}

Nothing more. Back to our example: you are building your markup until you have to insert an image. Easy peasy, you simply add the .float-left class to the image, and it’s done. Now you can go back to your CSS file with class/ID targeting and such. Maybe another example?

.hide {
display: none;
}
.show {
display: block;
}

You want to hide or show some of your elements for some reason. Instead of targeting an element directly and add display: none, you simply give it the .hide class.

This can also make your JavaScript development a lot easier. Imagine, you want to show those X items you set to display: none? You can now simply target all elements with the .hide class.

I think you get the point of these shorthand classes. They are not much than just a single CSS property, but thanks to them, you don’t have to go back to your CSS files and struggle with CSS selectors.

Design-related snippets

If you have read “Basic Ready-to-Use CSS Styles”, you already know some examples of design-related snippets. Those are little classes you can easily set to your elements in order to make the design process lighter and simpler, and to keep some kind of common style. Let’s dig a little bit into it, shall we?

Let’s start with something you’ll need in pretty much every single project you’ll ever work on: font styles. Creating some appealing combination of font-size, line-height and fonts can be tricky. Let’s make a few that will easily cascade through our document.

First, it changes the default font styles for your main content. The idea is to apply this to the root element in order to let it cascade to all elements.

Second, it gives some emphasize to any element with the .title class with a classy serif font. Adapt it to suit your needs.

Last, it gives code elements (inline or block) some special styles with a monospace font and a smaller font size.

It may seem silly, but it can be a huge time saver when you don’t want to specify font styles every single time you use a new element. Just add the according class, and let the cascade do the rest.

Maybe something a bit more practical now: a “disabled” class. “What for”, you ask? Whenever you want to show something is being disabled simply add the .disabled class (or whatever you’d like to call it). First of all, it will turn its opacity to 0.5, but more importantly, it will disable all pointer events on it (hover, click, etc.).

.disabled {
pointer-events: none;
opacity: 0.5;
}

A live example would be to give this class to the submit button of a form as a default. When every required field is properly filled, remove this class with JavaScript. Clean and simple, it helps the user understand he did everything right.

Important: don’t forget to add some server side verification. CSS and JavaScript can easily be manipulated. ;)

Another very easy example taking advantage of powerful CSS selectors would be the well known snippet which will give tables a Zebra look:

table tr:nth-child(even) {
background: rgba(0,0,0,0.1);
}

Note: you could also use the odd keyword for the nth-child property to target odd numbers. And of course you can pick whatever color you want. ;)

Development-related snippets

In the last section, we saw a few snippets which may be considered as design improvements. It means your design won’t break or look crappy if you omit them but it will look nicer if you use them. In this section, we will have a look at CSS snippets which are a less “design-related” but more related to the structure or development-related. Hard to tell, best explained with examples. So let’s go.

The first example is very easy. You’ve probably seen it many times before, especially since Paul Irish encouraged people to use it a while back:

In case you don’t know what the box-sizing property does: it’s used to alter the default box-model used to calculate widths and heights of elements. The default box-model is set to “content-box” which means it does not include padding and borders into the width value. This can be a huge pain in the butt, especially when it comes to responsive web design so we use a clean box-model: border-box.

A great example of using this would be to set some element’s width to 100% and add lateral padding to it. The default box-sizing would make the width be 100% plus the padding but using border-box would include the padding in the width. You can read more about it in this W3C working draft: CSS Basic User Interface Module Level 3 (CSS3 UI)

If you’re wondering about browser support, it is supported in every major browser, mobile ones included, excepted for Internet Explorer 7 and prior. A polyfill for those browsers exists if needed.

Note: it turns out that pseudo-elements are not included in the universal selector, so if you want your pseudo-elements to have a proper box-model like everything else, you should include them in the declaration.

Let’s continue with another very popular one: the clearfix. You know the song: when an element only contains floated elements, it collapses on itself. To prevent this behavior, you have to “clearfix” it. We used to do it with an extra element, but not anymore.

Note: The space content is one way to avoid an Opera bug when the contenteditable attribute is included anywhere else in the document. Otherwise it causes space to appear at the top and bottom of elements that are clearfixed.

Note: The use of display: table rather than display: block is only necessary if using the :before pseudo-element to contain the top-margins of child elements.

Enough with the common stuff, let’s get to something a little bit more underground!

This is the “visually hidden” class taken from the HTML5BoilerPlate project. What’s the point when we have display: none you ask?

Setting display: none hides content for screen readers and search engine bots. This is the difference that really matters. When you’re making tabs or playing with slideToggle(), don’t hide the content with display: none because you will make it unavailable for both, screen readers and search bots. Instead give it the previous class.

While we are talking about hiding stuff, let’s deal with image replacement. We all know what image replacement is:

Take an element

Give it a background-image

Hide the text

Some of you have probably done this with position: absolute; left: -9999px; since the dawn of time. Yes, it works. But it’s incredibly heavy for the browser to create a 10000px box, so here is a “new” way of doing it by Scott Kellum:

.ir {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}

When you look at the code, this is incredibly clever. It only moves the text out of the box. Nothing more, nothing less.

Now we will see two snippets about long strings truncation: one preventing the text to break out of their container (such as an URL) by forcing the break. And one to make an ellipsis in case the string is too long for its container.

Okay, there are many things to note here. Let’s start with the color stuff. You have probably understood the point of turning everything into black and white: saving money. Do you know how much a color ink cartridge costs? :D

The first four lines take care of 75% of the job by turning the font color to black and removing backgrounds and shadows.

The filter stuff mostly takes care of images by desaturating them. Internet Explorer uses an old proprietary filter, Chrome supports new CSS3 filters and for the others there is SVG.

A few days ago Christian Schaefer released a JavaScript polyfill for CSS filters using the unprefixed syntax getting back to Internet Explorer 6 (!).

This was about the grayscale thing. Now, what about anchors?

Since we removed colors, we’re back to the old-fashion way to show links: with an underline.

If anchors have a href attribute (and they should), we show their content after them.

Enough with the print. Let’s talk about something very trendy. Yes, you know what I’m talking about: retina displays! You know, those sweet little devices with a high resolution forcing us to recreate all of ours images twice as big. :)

Anyway, you may want to target only retina displays with CSS in order to, let’s say, override background images, or similar. There you go:

@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and ( min--moz-device-pixel-ratio: 2), /* Looks like a bug, so may want to add: */
only screen and ( -moz-min-device-pixel-ratio: 2),
only screen and ( -o-min-device-pixel-ratio: 2/1),
only screen and ( min-device-pixel-ratio: 2),
only screen and ( min-resolution: 192dpi),
only screen and ( min-resolution: 2dppx) {
/* Your retina specific stuff here */
}

Last, for the miscellaneous section, a CSS diagnostic snippet. Maybe you haven’t heard about it so much since it’s not really common. The idea, is to provide a block of code you activate when you want to do a little “validation” of your markup. Eric Meyer and Neil Grosskopf have provided some excellent resources.

Basically, you add the .debug class to the root of the document (the html element) and depending on your markup, you may see some elements bordered. From there, you decide what to do. ;)

Important: this doesn’t guarantee you to have a valid markup. In order to do this, please use the W3C validator.

Note: to improve the quality of your CSS, please have a look at CSSLint.

Mixins (CSS preprocessors)

In the first part of this tutorial, we saw a lot of things you can add in your style sheet in order to ease the development process. I think it’s time to have a slight glance at CSS preprocessors-related snippets.

Important: I won’t explain in detail what CSS preprocessors are, nor will I try to convince you to use one, or use a specific one.

A CSS preprocessor allows you to use variables, mixins, functions, operations, nesting, importing and much more. For that concern, I personally use LESS but there are also Sass or Stylus which might fit your needs.

Anyway, I’m only going to talk about mixins here. Mixins are like variables but for whole classes. The best point of mixins is that they can behave like functions and have parameters.

Let’s start with something very simple: a mixin to handle all vendor prefixes whenever you want to apply a transform to an element.

What does this mixin do exactly? It takes as a value all 0.3s ease-out if no value is specified. This is where it’s getting interesting. From now on (unless I want a very specific transition) I don’t have to set a value to transition anymore. I only have to do this:

We often associate preprocessors with CSS3, mostly because of the power of these previous examples, but you can of course, do perfectly valid CSS2.1 with preprocessors and find plenty of cases where you might “need” them. Please, have a look at the following code:

How cool is that? I’ve waited for ages to have a shorthand for this. I always found it annoying to have to type the 4 placement properties over and over again. We could even tweak it to include the type of position.

I’d like to end with a very useful mixin mixing (see what I did there?) CSS2.1 and CSS3 in order to provide something which could be very annoying to do manually: a rem/px converter.

Rem stands for “root em”. Its behavior is similar to the em unit except that it’s relative to the root element, not its parent element. Every major browser now supports it except Opera Mini and Internet Explorer 6/7. For those browsers, we have to provide a fallback in px.

Final words

As a final word, I will encourage you to create your own CSS snippets, whatever they are, as long as they increase your productivity and ease of development. Be sure to share them! ;)

Believe me or not, I code much faster since I started to do those things. I’m not even talking about CSS preprocessors here. I’m talking about making some default classes in order not to boot from scratch.

And if you’re using a CSS preprocessor, be sure to create a bunch of mixins to start your project with a solid basis. From there, CSS becomes a game again. ;)

If you’d like to download the CSS and LESS files with the snippets we have discussed, here you go: Download Snippet Files

Credits

We spoke about a bunch of topics today, so here are some useful resources and references:

Feedback46

Some of you have probably done this with position: absolute; left: -9999px; since the dawn of time. Yes, it works. But it’s incredibly heavy for the browser to create a 10000px box, so here is a “new” way of doing it by Scott Kellum: