There are many ways to select elements. Explore best practices and guidelines for usage.
- [Instructor] With so many ways to target HTML, how do you know which selector to use? Let's go over some guidelines for writing thoughtful and efficient CSS. Use type selectors when all or most instances of an HTML element needs to be styled in the same way. Use classes to select elements that are more specific, reusable and flexible than type selectors. The class name is the selector, so the style can be applied to any element.
Also, the same class can be used one or more times per page. ID values can only be used once per page, so stick to using them for unique styles and global elements that are not repeated. ID values need to be unique for another reason as well. They can also be used for in-page linking. Let's take a look at a sample frequently asked questions page. Adding an ID attribute to the element and using the value in the link's href attribute, will automatically take you to the matching element on the page when you click on the link.
A unique value is needed so the href attribute doesn't try to match more than one element on the page. Personally, I like to use classes only for CSS and reserve IDs for in-page linking. You can definitely still use IDs for CSS, but just remember to stick to the rules. Use descendant selectors when you want to apply a style to the element based on its parent or ancestor element. For descendant selectors, try not to go more than three levels deep.
Using more may result in a slower page load because the browser has to cycle through each pattern. Too many levels may also make your selectors too specific because they will only apply to the exact pattern. If you are looking to just style the paragraphs in the section in this example, section p works much better and is more efficient. Combine multiple selectors when you have different elements to apply the same styles to. This way you can target multiple elements in the same block.
When multiple selectors are combined, always declare the full combination if you're using descendant selectors. 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. 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.
- Creating a CSS file
- Writing basic selectors
- Setting properties
- Using different typefaces and web-safe fonts
- Understanding cascading and inheritance
- Setting a font family, font size, text color, and more
- Understanding the box model
- Using the float property