Tips on optimizing CSS

Tips on optimizing CSS

There are many reasons to optimize code for a website. First, it is a known fact that page loading time could affect potential conversions on a website. Second, optimized code is usually more organized. It is common for developers to work as a team, and the code you write as a developer should be clean and concise so it is easier to understand for other developers. Plus, it is just good web development practice to keep your code optimized.

Personally, I love CSS, and a lot of my blog posts are about CSS. A fellow developer here at Blueprint shared some tips a while ago on keeping your code clean, and today I will be sharing more tips on optimizing CSS.

Combine all CSS into one file

This has more to do with optimizing the page load time. Reducing the number of CSS files means reducing the number of HTTP requests. Keeping all your CSS in one file will prevent extra code from floating around on a website, and your code will be better organized.

Use CSS shorthand properties

#foo {
	margin-top: 20px;
	margin-right: 5px;
	margin-bottom: 20px;
	margin-left: 5px;
}

You may not care about how many characters, line breaks, and spaces you are using because they normally do not take much space. However, if you have a lot of CSS in a file, the file size will get too large before you might realize. The code above is very wordy. Why list out each property when you can combine them? The above could be shortened to:

#foo {
	margin: 20px 5px 20px 5px;
}

…which could be further shortened to:

#foo {
	margin: 20px 5px;
}

Writing CSS properties in shorthand will reduce the file size and make your code optimized.

Group styles

#foo {
	margin: 20px 5px;
}

#bar {
	margin: 20px 5px;
}

Did you know you can group CSS selectors that use the same style? The above code could be shortened to:

#foo, #bar {
	margin: 20px 5px;
}

Keeping like styles together will make your code shorter and easier to scan for other developers.

Reuse CSS classes

I touched on this in my blog post Handy CSS Tips for Responsive Design, but if you have a similar style that needs to be used across the website, it is a good idea to make one CSS class that has the common CSS styles. For example, if all the buttons have the same style, you could write CSS styles for one class called .button, as shown below:

.button {
	display: block;
	width: 100px;
	height: 30px;
	font: normal 1.5em Arial, sans-serif;
	text-align: center;
	background: #fcecfc;
	background: -moz-linear-gradient(top,  #fcecfc 0%, #ff7cd8 100%);
	......
}

Conclusion

There are more steps you could take if you are looking to reduce the CSS file size such as minifying your CSS file. It is also a good idea to keep your code organized by grouping some CSS selectors together in sections and adding comments. Following the above tips can make your code cleaner during the development process.

By: Blueprint