Web Dev

Applying CSS Rules: Elements, IDs, and Classes

HTML Elements

There are three different selector types that you can use to apply CSS rules to HTML elements. The first is simply to use the element as the selector. You can use this for any element: headings, paragraphs, etc.

The CSS rule you apply to an HTML element will be applied to all of those elements within that document. For example, if you apply a style to your <p> element, it will apply the style to every paragraph in the document.

Here’s an example of styling your <p> tag using CSS. You’d see the following rule in an external stylesheet (a .css file) or in <style> tags.

p {
    color: blue;
    font-size: 20px;
}

#IDs

Classes and IDs are two additional ways to label HTML elements so you can apply CSS styling to them. While it’s up to you what you want to name your classes and IDs, it’s best to name them in a way that describes their purpose. It will make reading your code much, much easier.

IDs can only be used once per page. IDs are good if you want one, specific HTML element to stand out with CSS styling.

<!doctype html> 
<html> 
<head>     
     <title>Hello world!</title> 
     <style> 
     #contact-header {color: black; text-transform: uppercase;}

     </style>
</head>
 
<body> 
<h2 id="contact-header">Contact</h2>
</body> 
</html>

After you add an id in the HTML tag, you target the id with a pound symbol (#). Whenever you see a pound symbol, know it’s saying, “ID of.” In the example above, we target the ID of contact-header.

Note that IDs can’t use spaces, so stick to hyphens or camel case when naming them.

.Classes

Classes can be used any number of times: there are no limits! If you want to add styling to elements that appear more than once on a page, using a class is the way to go.

You can add classes to a div (remember, a div is a generic container spanning multiple lines) or a span (generic inline container). Instead of a hashtag, you call these calls with a period, which means, “Class of.”

<!doctype html> 
<html> 
<head>     
     <title>Hello world!</title> 
     <style> 
     .nav {background: gold;}

     </style>
</head>
 
<body> 
<span class="nav">Contact</span>
</body> 
</html>

Every element with the class of “nav” will now have a gold background. Classes are good for keeping your styling consistent.

The more specific, the better

The declarations of a more specific selector will always override the declarations of a less specific selector.

In order of most specific to least specific selector:

  1. IDs
  2. Classes
  3. Elements (generic HTML elements, such as h2, h2, h3, etc.)

If you’re writing a rule, and you just aren’t seeing your changes applied, chances are, it’s because a more specific selector is overriding your changes.

Learn more about classes, IDs, and specificity in Don’t Fear the Internet: Targeting Classes with Classes and IDs.