Best Practices for Selecting Elements

There are so many ways to target HTML with CSS, like I have shown you. So, how do you know which selector to use? This lesson contains best practices for selecting HTML elements.

We'll cover the following

Let’s go over some guidelines to help you write better and more efficient CSS.

1. Use type selectors when all or most instances of an HTML element needs to be styled in the same way.

For example:

	
  h1 {
  	color: red;
  }
  

Where h1 represents any type selector. This will style every h1 in the document. It is appropriate to use this selector when you’re sure you want every element to look and feel the same way.

2. Use classes to select elements that are more specific, reusable and flexible than type selectors.

For example:


	.red-letters {
  	color: red;
  }
  

The class .red-letters may be applied to multiple HTML elements, and they will all have the color of red.

This fosters reusability and flexibilty.

3. ID values can only be used once per page, so stick to using them for unique styles and global elements that are not repeated.

For example:

	
  #my-element {
  	color: teal;
  }
  

IDs in HTML are unique. They should not be added to multiple elements. By implication, styles set on an ID element cannot be reused. Stick to them only for unique styles that are not repeated.

4. For descendant selectors, try not to go more than three levels deep.

For example:

This looks good:


	div .red-letters {
  	color: red;
  }

This is too much

	div .red-letters h1 p {
		color: red; 
  }

It does work, but using more selectors may result in a slower page load because the browser has to cycle through each pattern.

This is generally frowned upon. I dont want you writing messy code.


Conclusion

No two projects are exactly the same, so it will take practice and experience to get to know which selectors are best for each scenario.

This comes with experience, so don’t sweat it now.

When you’re learning, the first step is just being able to make it work. Once you have that under your belt, you can always go back and see where you can improve and revise.

Get hands-on with 1200+ tech skills courses.