Events in CSS
5. Best Practices in CSS
When coding in CSS, there are some practices that will make work easier. It will make debugging the code faster and makes collaboration with others easier. Given below are some best practices that you can do when coding:
- Code your HTML first.
CSS is used to design your web page. It will be difficult and very unorganized to do a bit on HTML, then do CSS, then return to HTML, then CSS again.
- Make your code readable.
Always observe proper indentation and new line spacing where needed. Given below are two versions of the same code with different line spacing.
Version 1:
h1{
color: red;
text-align: center;
border: 1px solid black;
}
Version 2:
h1{color: red; text-align: center; border: 1px solid black;}
Which line spacing technique do you think allows for easier and faster reading of code? Version 1 allows for better reading. Assume also that you have to edit the code later on. Which line spacing technique do you think allows for faster location of the line of code that needs to be modified? It’s version 1.
- Group selectors with the same formatting together
Let’s say you have an <h1> tag, a <p> tag, and an <h2> tag with the same formatting. You can group them by using commas so that the set of properties you will use for their formatting will only be declared once. Look at the code snippet below for an example:
h1, h2, p {
color: red;
text-align: center;
border: 1px solid black;
}
- Learn to use the short-hand property of CSS properties
There are multiple CSS properties whose values can be declared in a single line by using the shorthand for these CSS properties. Examples include margin, border, and padding. Look at the code snippets below for an example:

- Avoid using inline CSS and use external stylesheets as much as possible.
This provides a more unified location for all CSS formatting for your project. Whenever you need to change or modify the whole website's formatting, using external style sheets allows you to modify only a single file. Using internal and inline CSS would mean that you have to visit all the HTML files in your website to modify the CSS code in each file.
- Organize your CSS code
It’s good practice to always start from the top and work your way down to the bottom. For example, at the top of your CSS code, the formatting for header elements should be found, then below them are formatting for the content, and then at the bottom of the CSS code is the formatting for the footer section of the website.
Aside from top to bottom, structure your code to have the general formatting for containers
first, and then work your way inside into the container's specific contents. For example, if you have a
div element that contains an image and a paragraph, type the code first for the div (i.e., padding,
margin, border) and then type the code for the paragraph and the image after the div