CSS is not very hard to use or learn, though it may be hard to master. Moreover, if you use CSS for your projects, especially when they are large projects, it can be very hard if you do not follow certain tips to help you manage the CSS code better. By following certain tips to writing better CSS code, you can make your life so much easier, as well as improving your project. When it comes to CSS, little tweaks in the code can make a big improvement, which can make you work more efficiently and have a better outcome. Today, I have written 19 tips that will help you write better CSS code for your projects. I hope you find my tips helpful, and feel free to leave a comment if you have a questions or have any additional tips to share! I love hearing from fellow CSS enthusiasts! Enjoy!
Use Meaningful Names
In CSS, as with every language, it is very important to use meaningful and descriptive names for our elements. This increases the readability and the maintainability of our code. A classic example of a bad naming convention is having a two columns layout, which the column that contains the menu has an ID of ‘leftcol’ and the content is named ‘rightcol’. Right now the content is fine, but what about if you need different stylesheets for different visitors or requirements of your client? For example if your client wants to swap the columns positions? Then the columns have the wrong names.
The best solution is determinate which one is the main content and which one is the secondary one. The main content should be named “maincontent” and the secondary one should be named “secondarycontent.” This will solve the problem of swapping column position and it is clearer for maintainability of our CSS.
No ID’s, Generalize with Classes
A common mistake made by web developers is using ID almost for everything, which it is effective if we are working in JavaScript, because it is the fastest way to get an element; however, using IDs in CSS reduces the reusability of our code drastically. For example:
#formExample1{ border:1px solid gray; padding:20px; } #formExample2{ border:1px solid gray; padding:20px; }
We are not reusing code at all because we are using the same styles for different ID, which is a waste of time and increases the amount of unnecessary CSS code; we can write this in a better way using a class. For example:
.form{ border:1px solid gray; padding:20px; }
Another example that reduces the reusability is the use of complex selector to style a simple element. For example:
div.error-message{ color:red; }
For maintainability purposes, it is better to rename this selector just to .error-message, and we now can use this style in all elements we want to.
Use Inheritance and Cascade Properly
Most of the time people forget that elements inherit the styles of their parents and create unnecessary classes to style those elements. Example, to create a zebra table it is common to see this:
.odd{ background-color:#E9EBEB; } .even{ background-color:#9EB0EE; }
The implementation of this in a table used like this:
<table> <tbody> <tr class="odd"><td>Lorem</td><td>Ipsu</td></tr> <tr class="even"><td>Lorem</td><td>Ipsu</td></tr> <tr class="odd"><td>Lorem</td><td>Ipsu</td></tr> <tr class="even"><td>Lorem</td><td>Ipsu</td></tr> </tbody> </table>
It would be better to give a background-color to the table’s body and just look for the even or the odd positions and style it. This would save time and code. For example, we are going to style only the even elements:
table tbody{ background-color:#E9EBEB; } .even{ background-color:#9EB0EE; }
<table> <tbody> <tr><td>Lorem</td><td>Ipsu</td></tr> <tr class="even"><td>Lorem</td><td>Ipsu</td></tr> <tr><td>Lorem</td><td>Ipsu</td></tr> <tr class="even"><td>Lorem</td><td>Ipsu</td></tr> </tbody> </table>
I know that we can use CSS to select the even and odd elements of a table, but it is not supported by all the browsers yet.
Namespacing
Namespacing is a good way to use cascade and avoid the use of class for everything in our html. For example, image that you have to create a widget and the title of the widget is going to be an h3 tag, we can use a class for the widget and namespace everything that is related with that class, for example:
.widget{ width:300px; height:200px; border:1px solid gray; } .widget > h3{ color:white; background:black; padding:10px; }
<div class="widget"> <h3>Weather Details</h3> </div>
Optimizing Does Not Uniforming in All Browsers
One of the most difficult parts of CSS coding is making it work right in all major browsers; however, some developers wants to go beyond and make every pixel look the same in every browser, which is a huge mistake, because it is necessary to create a lot of hacks and styles just to create an effect that is not available in an specific browser. An example of this is a round border; if the round border is only for esthetics purposes, why just not leave that feature for the browsers that really support it. Why create images for a round border that most of the time the user doesn’t even notice?
When I get asked about making things the same in all browsers, I send the the person to the site Do websites need to look exactly the same in every browser?, and I know he will get the answer pretty quickly .
Better Markup to Avoid Classitis and Divitis
We still see a lot of sites with horrible markup, using unnecessary numbers of divs and spams. It is still common to see div elements surrounding unordered list to create menus like this:
<div id="menu"> <ul> <li>Home</li> <li>Products</li> <li>Services</li> <li>About Us</li> </ul> </div>
This menu could be used exactly the same avoiding the parent div. For example:
<ul id="menu"> <li>Home</li> <li>Products</li> <li>Services</li> <li>About Us</li> </ul>
This not only cleans up our HTML code, also it cleans our CSS because instead of referring to a parent to create an effect we can target the element directly.
Avoid Inline Styles
Everybody knows that inline styles are a very bad practice and should not be used. Inline styles reduce the reusability and portability of the code to its minimun expresion, in addition, it is very hard to maintain and use as the CSS is meant to be used overwriting all the inherited styles.
Avoid Hacking your Code
Every version of every browser has bugs and they are targeted in different ways into the stylesheets. The main case is Internet Explorer which has been very painful for developers when trying to design and code cross browsers websites. When I talk about avoiding hacking your code, what I mean is adding In-CSS hacks instead of conditional comments. I prefer to keep my code understandable and clean using an extra style file for that specific version of internet explorer, so if another programmer of designer needs to modify the code, he or she would not have the headache of not knowing what the In-CSS code means.
Reset the CSS
Using a reset file, ensure that you do not need to work with browser differences. Additionally, it creates the base framework to make sure that our styles are going to work properly in all the browsers. You can use the Eric Meyer’s CSS Reset or YUI 3: CSS Reset in your projects. (If you use a framework, for sure that you would have it included in the files of it).
Selecting a Framework
A while back, I used to think that CSS frameworks were unnecessary, and if you know CSS you are ready to go and do not need anything else. But, after I worked with YUI and 960 I changed my mind and saw how easy I can create layouts using those frameworks. Also, a framework is a good way of reusing code and keeping a consistent coding style.
Other frameworks are Blueprint, Elastic, and YAML.
Comment your Code
Commenting is the best way of keeping your code understandable and maintainable. Think about working in different projects at the same time, where you have to modify some elements or styles. If you do not have a very organized style in your comments, you would end up consuming a lot of time trying to understand what you did some weeks ago. Comments come to help you and the others programmers to easily understand what that snipe of code is about.
I usually divide the CSS in four blocks: Reset, Layout, Pages, and Miscellaneous. For example:
/* Reset */ ..Restet the browser default.. /* Layout */ ..Code for Layout only, including Forms.. /* Pages */ ..Code that is used for specific page or pages. /* Miscellaneous */ ..Code for messages div, alerts, lightbox, etc.
I use the suggestion of Douglas Crockford for commenting the code in JavaScript where he states to comment only what is not immediately visible.
Use Shorthands
It is always recommended to use shorthands to keep the code compact. It would reduce the time we spend coding our CSS, and also it its more optimized because it reduces the file size of our stylesheets. For example:
.example { width:200px; height:100px; background-color:#CCCC66; border-top-color:#333333; border-top-style:solid; border-top-width:1px; border-bottom-color:#333333; border-bottom-style:solid; border-bottom-width:1px; border-right-color:#333333; border-right-style:solid; border-right-width:1px; border-left-color:#333333; border-left-style:solid; border-left-width:1px; }
The above example could be replaced by this:
.example { width:200px; height:100px; background:#CCCC66; border:1px solid #333333; }
Obviously, this is not only result in a reduced file size for your page load, it is also less code and easier life for a developer.
Pick a Style and Stay with It
Everybody has their own programming styles, and in CSS it is no different. Some developers like to keep all the declarations in one line, some prefer to use one declaration per line, and others group order the properties alphabetically. My recommendation is to pick one style or even a mixture of some and stay with it in the whole project. In addition, try to use the one that works best for you, and the one you feel more comfortable with. Remember, that at the end it has to work for you, if not you are wasting your time.
Look for Repetitive Code
After you are finished with your project, it would be nice to look for repetitive code or patterns and convert them into classes. For example, you use the same background and color for different parts of the projects, and it would be a good idea to add these properties into a class and reuse them. This would avoid the repetitive code, and it makes it very easy to maintain.
Use Sprites
Every image that we include in our design makes a request to the server to be loaded into the page. If we use sprites, would reduce considerably the amount of requests. Also there is another alternative for this issue posted by Nicholas Zakas in his blog named “Data URIs make CSS sprites obsolete“.
Object Oriented CSS
The certified CSS Ninja, Nicole Sullivan came out with the idea of OO CSS which is focus in the reusability and build our CSS components as small legos. It is worth checking out!
Follow the Masters
There are a lot tutorials online, but I would recommend to go directly to the people that created them or even inspire them. There are a few folks that I recommend to visit their pages and read to understand CSS better. To mention some, Chris Coyier, Eric Meyer, Stu Nicholls, Nicole Sullivan, Andy Budd, Alen Grakalic, and a bunch of sites to help you to learn CSS.
Validate your CSS
To ensure that your code works properly in all the browsers it is good to validate it. When we validate the code, we can find some mistakes that we had made in the development phase. That is why it is always recommended.
Minify your CSS
Before you put it in production, you should compress the CSS by deleting the whitespaces and comments, which could reduce the file size of your stylesheet up to 40% of its original size. This maximizes the user experience, because the page will load a little bit faster.