25 Incredibly Useful CSS Snippets for Developers

CSS is no doubt up there with the most important web languages that we use. While html provides the structure it can be inconsistent and unpredictable across different new and old browsers. Css is where the html is styled though, and where we get creative as well as addressing those inconsistencies. Below is a fantastic list of 25 Css snippets that I am sure you will find extremely useful. Whether you are a veteran web developer, or are just getting your foot in the door of css, they are all well worth checking out.

Hide text with text indent

This is extremely useful for use for things such as your company logo. More often than not, it’s an image, but you’ll want to display it in h1 tags for SEO as well. Here’s the best way to do so. What we basically do is hide the text far away off the screen, and apply a background image instead.

h1 {
	text-indent:-9999px;
	margin:0 auto;
	width:400px;
	height:100px;
	background:transparent url("images/logo.jpg") no-repeat scroll;
}

Style links depending on file format

This snippet is aimed at user experience. Often on the internet we find ourself clicking on links knowing nothing about where we are heading. This snippet can be used and expanded to show small icons next to your links telling the user if it is an external link, an email, a pdf, an image, and so much more.

/* external links */
a[href^="http://"]{
	padding-right: 20px;
	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: 20px;
	background: url(pdf.png) no-repeat center right;
}

Remove textarea scrollbar in IE

Internet Explorer has an annoying habit of adding scrollbars to textarea’s even when the textarea’s content is not overflowing. You can rectify this flaw with this easy to use snippet.

textarea{
	overflow:auto;
}

Drop cap

Commonplace these days in blogs and news sites is the dropcap. You’d be surprised at how easy it is to implement, and how well it degrades for older browsers.

p:first-letter{
	display:block;
	margin:5px 0 0 5px;
	float:left;
	color:#FF3366;
	font-size:60px;
	font-family:Georgia;
}

Css Transparency

Transparency is something that isn’t done the same way across browsers which can be annoying. Here’s how you can target transparency in multiple browsers.

.transparent {
	filter:alpha(opacity=50);
	-moz-opacity:0.5;
	-khtml-opacity: 0.5;
	opacity: 0.5;
}

Css Reset by Eric Meyer

Eric Meyer’s css reset has become almost standard now days for use at the start of your stylesheet. Having been adopted by some of the most influential designers, you can be sure of its quality.

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, font, 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 {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	vertical-align: baseline;
	background: transparent;
}

body {
	line-height: 1;
}

ol, ul {
	list-style: none;
}

blockquote, q {
	quotes: none;
}

blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}

/* remember to define focus styles! */
:focus {
	outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
	text-decoration: none;
}

del {
	text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: collapse;
	border-spacing: 0;
}

Image preloader

Sometimes it is useful to pre-load your images so that when a certain element is needed, they’ll already be loaded for you and there wont be any delay or flickering.

div.loader{
	background:url(images/hover.gif) no-repeat;
	background:url(images/hover2.gif) no-repeat;
	background:url(images/hover3.gif) no-repeat;
	margin-left:-10000px;
}

Basic css sprite button

Having a button or link with a background image is fairly normal, and nowadays, we require further effects to enhance the user experience. Once of this is an indicator to the user that they are hovering over a button. Using a sprite, we can create this effect by changing the position of the background image down a certain height to show the background to the button on hover. A simple yet effective technique.

a {
display: block;
background: url(sprite.png) no-repeat;
height: 30px;
width: 250px;
}

a:hover {
	background-position: 0 -30px;
}

Google Font API

Google recently released a fantastic resource for web designers allowing them to load new fonts from google for use in our web pages. We can even load different variants of fonts such as bold, italic and so on. While the library of fonts available from google is limited, there is still plenty to use. First include the dynamically written stylesheet by naming the fonts and variants you want, and then use the font names in your css as you normally would! For further info on Google Font API, read here.

<head>
	Inconsolata:italic|Droid+Sans">
</head>
body {
	font-family: 'Tangerine', 'Inconsolata', 'Droid Sans', serif; font-size: 48px;
}

Browser specific hacks

Sometimes it’s useful to target specific browsers to fix their inconsistencies and conditional comments aren’t always the best way to do so. This list of css browser hacks by Chris Coyier is a top-notch list of ways to target browsers with simple css.

/* IE 6 */
* html .yourclass { }

/* IE 7 */
*+html .yourclass{ }

/* IE 7 and modern browsers */
html>body .yourclass { }

/* Modern browsers (not IE 7) */
html>/**/body .yourclass { }

/* Opera 9.27 and below */
html:first-child .yourclass { }

/* Safari */
html[xmlns*=""] body:last-child .yourclass { }

/* Safari 3+, Chrome 1+, Opera 9+, Fx 3.5+ */
body:nth-of-type(1) .yourclass { }

/* Safari 3+, Chrome 1+, Opera 9+, Fx 3.5+ */
body:first-of-type .yourclass {  }

/* Safari 3+, Chrome 1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
 .yourclass  {  }
}

Fixed Footer

You would think creating a footer that sticks to the bottom of the screen would be rather hard, but surprisingly it isn’t if you want to start with a basic footer. There is an IE6 hack we have to use, but apart from that, it’s easy!

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

/* 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');
}

Flip an image

Flipping an image rather than just loading a new image that is already reversed can be rather useful. Say you want to use only one image for an arrow, but have several on the page going in different directions. Here’s your problem solved.

img.flip {
	-moz-transform: scaleX(-1);
	-o-transform: scaleX(-1);
	-webkit-transform: scaleX(-1);
	transform: scaleX(-1);
	filter: FlipH;
	-ms-filter: "FlipH";
}

Clearfix

A while back, someone decided it was time to clear floated elements without adding any extra markup to the document. They did this by creating a class that can be applied to the container of floated children to clear it. A fantastic way to do so, and something that is nowadays, widely used.

.clearfix:after {
	visibility: hidden;
	display: block;
	font-size: 0;
	content: " ";
	clear: both;
	height: 0;
}

.clearfix { display: inline-block; }

/* start commented backslash hack \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* close commented backslash hack */

Rounded Corners

With the slow introduction of css3, rounded corners have been made easily possibly in modern browsers. Sadly we still don’t have css3 support for IE, but it will be available in IE9 whenever that is released.

.round{
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	border-radius: 10px; /* future proofing */
	-khtml-border-radius: 10px; /* for old Konqueror browsers */
}

Style Overriding

It still surprises me that some people don’t know about !important in css, because it is such a powerful and useful tool to have. Basically, any rule with !important at the end, will override any of the same rule that is applied to that element wherever it appears in the css file, or in-line html.

p{
	font-size:20px !important;
}

Font face

Font-face didn’t really break through until late last year, but has been around since the days of IE6 being a modern browser! It’s picked up in support a lot now though, and offers a great way to use non web safe fonts in your web projects. While this snippet works, you might as well save your time by using the Font Squirrel Font Face Generator.

@font-face {
	font-family: 'Graublau Web';
	src: url('GraublauWeb.eot');
	src: local('☺'),
		url('GraublauWeb.woff') format('woff'), url('GraublauWeb.ttf') format('truetype');
}

Center a website

A common design trend these days is for your website to center itself in the middle of browser’s viewport horizontally. This is an easily achievable thing to do.

.wrapper {
	width:960px;
	margin:0 auto;
}

Min-height in IE

This comes down to fixing a simple, yet annoying bug in IE’s capability of handling min-height. In essence, IE interprets height as min-height, so since IE wont implement the auto height, this snippet will fix all this for us.

.box {
	min-height:500px;
	height:auto !important;
	height:500px;
}

Image loading

This image loading effects mimics that of an ajax loader, where a loading circle is displayed while content loads. This works especially well for larger, slower loading images, and is css only!

img {
	background: url(loader.gif) no−repeat 50% 50%;
}

Vertical Center

This short snippet allows you to vertically center the contents of a container without any extra markup by simply displaying it as a table cell which then allows you to use the vertical-align attribute.

.container {
	min-height: 10em;
	display: table-cell;
	vertical-align: middle;
}

Create pullquotes

Firstly, what is a pullquote? Well in news and magazine style websites, you’ll often notice small quotes added within the article, not as full blockquotes, but as small quotes that sit within the article but to the side, sometimes adding things such as people’s opinions or quotes. They are extremely easy to create you’ll be glad to know, and when used properly, can add greatly to the user experience when reading an article.

.pullquote {
	width: 300px;
	float: right;
	margin: 5px;
	font-family: Georgia, "Times New Roman", Times, serif;
	font: italic bold #ff0000 ;
}

Text Selection

Some people are unaware that it is possible to change the color when you highlight text in your browser. It is so easy to with two selectors; just be careful you don’t ruin your site with it.

::selection {
color: #000000;
background-color: #FF0000;
}
::-moz-selection {
color: #000000;
background: #FF0000;
}

Print page breaks

This add’s again to the user experience when printing. For example, when printing an article, it may be useful for a user to have the comments on a new page from the article itself. by adding this class to the comments area, a page break will appear when printing. It can be used anywhere else on your site as well!

.page-break{
	page-break-before:always;
}

Further thoughts and discussion

I know for sure I haven’t been able to cover every useful css snippet out there, but have provided those that I think will benefit the most. What do you think about these snippets, and what do you think about others that are out there? If you know of some mighty useful css snippets, then bring them to the table in the comments, so we can see and discuss them!

Matthew Corner

Matt is an 18 year old web designer from Scotland, UK. He loves creating beautiful websites across different platforms. High on his things to learn fully are Jquery and php. He is extremely excited by css3 and html5 and can't wait to see them rolled out fully. To learn more about Matt, follow him @QwibbleDesigns, or check out his portfolio.

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. Tony says

    i always get stuck in some css issues that gets solved after some research but after reading this post looks like i won’t need to search for typical css issues that i always face. Thanks…

  2. jake says

    These are nice snips if you understand them, if you resort to copy-paste then you are in trouble.
    + for collecting them
    – for not explaining them

  3. Darren says

    Supper article. i will use this content to train my buddies. I’m very lazzy css coder i do find things like this but never try to collect it. thanks for collecting this important css code parts and publishing it.

  4. says

    First: Good post.. i want to translate and post on my blog can i ?

    Second: What is the name of this plugin that shows how many times this post have been digg, or re-tweet. ?

  5. George Columbow says

    Bravo, Matthew! Great little encyclopedia of CSS-snippets for everyone who build sites.
    Looking forward your the next articles about CSS and other useful things!
    Thank you!

  6. says

    Thanks for the list!! I have a question though – I really want to use the rounded corners snippet, but how do I use it? I copied and pasted the code you provided into a stylesheet and then tried assigning both the class “round” and the id “round” to different elements in my html page but it didn’t have any effect….any ideas?? thanks!

  7. says

    I have a question, why you wanna hide text from h1?

    text-indent:-9999px

    What is the point, to hide it? I think you can have logo and also text, which is best for SEO, or not?

    Look at my website, http://www.faiby.com
    all h2 tags are made with logo on the background and text is indented just a little, from logo, to be seen.

    Thx for responces.

    • Matthew Corner says

      What if you don’t want the text next to your logo? Not every company has a font in their logo that can be web embedded. Sure, you’re solution works for your icons next to titles, but for company logos at the top of the page in the header, no it doesnt.

  8. Thomas Craig says

    Matt, great list that is very useful. Few snippets listed that are an automatic inclusion in all new development/projects.

  9. james nnannah says

    Great post! Behold the power of css! Learnt great new simple useful stuff. Bookmarked on delicious!

  10. says

    You can’t beat a good set of snippets!

    This is a great list, thanks

    I’m adding a few to my snippet catalog now!

  11. says

    Some great tips here, thanks for sharing. It’s worth noting that when you’re applying CSS effects to :hover states it’s worth remembering to also apply the effect to the :focus state too. This is particularly valuable when using a reset stylesheet as the outline around focused links is often removed. Not great for those having to use a keyboard for navigation.

  12. mak kumar says

    Great Collection!!

    But i have request to you, whenever you post more tutorial or article please so upload their example too..

  13. says

    I liked all the CSS you listed Matt they are awesome.

    Some how I didn’t like the 1st one ‘Hide text with text indent’, as search engines can consider it SPAM (its just an alternative like hiding text with same background color)

    Rest all the CSS are very useful and helpful.

    @joydeep7

  14. says

    Thanks for bringing these together. Very useful to confirm the techniques I’m already using and some great new ones I had no idea about.

  15. says

    Thanks a lot this helped me out! I appreciate this. I’m just glad someone has some wisdom with css.

    Thanks again, Gary Great Article

  16. erwinbatucan says

    still a newbie on xhtml and css. this will be very helpful.
    thanks for sharing, its straight to the point and an easy read

  17. azuza says

    Instead of using text-indent to hide text and show an image you can wrap the text you want to hide in a span tag and just mark that selector span {display: none;}

  18. Jimbo says

    As Joseph pointed out, use overflow:auto OR overflow:hidden to clear floated children. The clearfix method is long gone.

    Conditional comments: Pretty rare that anyone would need to target Webkit browsers/Opera/only modern browsers. For IE, I’d only use conditional comments as they’re future-proof and hack free.

    I wouldn’t use the h1 as hidden text in place of the logo. h1 ought to give the initial context of the page – i.e. be the first actual heading, which would benefit SEO way more than your h1 being “Business Name” on every page.

    Otherwise a great collection, thanks for sharing.

    • Matthew Corner says

      I must admit, I wasn’t aware that overflow:auto also acted as a clearfix, but as my latest project proved to me, that, and overflow:hidden can still cause you more problems, and so clearfix is still relevant in my opinion. Sure, if auto or hidden works, and doesn’t muck up other areas of your design, then use it, but it’s not always appropriate =) Thanks for pointing it out though

      • says

        The {overflow:hidden;} fix works fine, except in ie 6 and lower (and maybe 7 i can’t remember) but if you apply a conditional comment to the page for those browsers and set {zoom:1;} on the elements that needed the overflow it will be fixed. I’m using this for years now and never had to use the clearfix anymore. This will keep your code a lot cleaner.

  19. bahar says

    Thanks for sharing.
    But I think that it is better to put some rounded corners without any css3 properties. Because using css3 to create a rounded corner is not a snippet, it is just a simple 3 lines css properties.
    Thank u again.

  20. Joseph says

    There is a new clearfix that is really really easy. Just use overflow:auto; on the container of the floated elements! Yes, it does work! And to think it took us years to find this out!

  21. says

    Some very nice tips there. The use of many of them should even be common practice! Really loved the css image preloader…

  22. says

    Thats a great collection of snippets – I knew of most of them already, but there are a couple that I hadn’t seen before…thanks.