The Beginner's Guide to CSS Classes & .class Selectors

Download Now: 35 Free Code Templates
Kristen Baker
Kristen Baker

Published:

Imagine you're designing a web page. You want a group of headings to have a large red text, a group of buttons to have a medium white text, and a group of paragraphs to have a small blue text.

Site owner using CSS classes and selectors to style HTML elements

Bold choices. But, thanks to classes in CSS, you can do exactly that. CSS classes enable you to apply unique style properties to groups of HTML elements to achieve your desired web page appearance.

In this post, we'll cover the fundamental terms you need to know, like CSS class, class selector, and CSS specificity. We'll also walk through how to create a class in CSS and use it to style your web pages.

Download Now: 25 HTML & CSS Hacks [Free Guide]

Let’s look at an example of how CSS classes work. Below, we have a simple HTML page with three headings (h2 elements) and three paragraphs (p elements).

Notice how the second heading, third heading, and final paragraph are styled differently than the rest — this is because these elements have been assigned the class bright. Looking at the CSS, we see the .bright selector, which applies its style rules to all elements with the attribute class="bright".

See the Pen css class: heading example by Christina Perricone (@hubspot) on CodePen.

You can use CSS classes to group HTML elements and then apply custom styles to them. You can make classes and apply them to text, buttons, spans and divs, tables, images, or just about any other page element you can think of. Let’s now take a closer look at how we can use CSS classes to style page elements.

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Beginner's Guide to HTML & CSS

Learn the basic definitions, differences, and codes to know for your website.

  • Intro to coding langauges.
  • HTML vs. CSS
  • Codes to Know
  • And More!
Loading your download form

You're all set!

Click this link to access this resource at any time.

Access now
Learn more

How to Create a Class in CSS

Let’s try making a CSS class from scratch. Say you want to make a paragraph of text and style certain words for more emphasis. You can do this by creating a CSS class for these special words, then assigning this class to individual words with span tags.

Start by writing out the HTML elements you want to style. In this case, it’s a paragraph of text:

<p>Our<span>marketing software</span> and <span>service platform</span> provide you with the tools you need to <span>engage</span> visitors, <span>convert</span> them to leads, and <span> win them over</span> as customers. </p>

I’ve also placed <span> tags around the words we’ll soon style with a CSS class.

Next, let's add class attributes to these <span> tags. To do so, add the attribute class="name" to the opening tag of the targeted element, and replace name with a unique identifier for the class.

a diagram showing how to create a css class

Image Source

In our example, the HTML looks like this:

<p>Our <span class="orange-text">marketing software</span> and <span class="orange-text">service platform</span> provide you with the tools you need to <span class="blue-text">engage</span> visitors, <span class="blue-text">convert</span> them to leads, and <span class="blue-text">win them over</span> as customers.</p>

Here we’ve added two CSS classes to our span tags: orange-text and blue-text.

Now, let’s go over some questions you may have about CSS classes.

Where Can You Add CSS Classes in HTML?

CSS classes can be added to any HTML element. Some of the most common include:

  • Paragraph (<p>)
  • Body (<body>)
  • Title (<title>)
  • Headers (<h1>, <h2>, <h3>, etc.)
  • Blockquotes (<blockquote>)
  • Spans (<span>)
  • Divs (<div>)
  • Images (<img>)
  • Buttons (<button>)
  • Embeds (<embed>)
  • Links (<a>)
  • Ordered lists and list items (<ol> and <li>, respectively)
  • Unordered lists and list items (<ul> and <li>, respectively)
  • Tables (<table>)

Put simply, if you have an HTML element, you can add a CSS class.

How Many CSS Classes Can You Add to an Element?

One of the most common uses of class in CSS is to add a specific style to a specific element.

Worth noting? You’re not limited to a single class per element. Consider paragraphs. While you can specify CSS classes for all paragraphs on your page — such as font size or background color — you can also specify classes for individual paragraphs to change their color or margins while still keeping the overall style changes intact.

In practice, you can add as many classes as you like to a single element, but it’s worth keeping track of what you’re changing to make sure you can revert to previous versions if the end result doesn’t match your expectations.

What is the Difference Between Class and ID in HTML?

The difference between class and ID in HTML is that IDs are unique — classes are not. In practice, this means that multiple elements on a page can have the class, while elements can have only one ID and each page can have only one element with that ID.

Consider a specific comment on a WordPress post. While you might use the “item” class to define all comments on the same page, you could also assign the dynamically generated WordPress value for the comment as its unique ID.

This is the only ID the element can have, and it cannot be repeated anywhere on the page. Using IDs allows you to easily locate specific elements, and ensuring the same ID is not repeated across elements is essential for your HTML code to render properly on the front-end.

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Beginner's Guide to HTML & CSS

Learn the basic definitions, differences, and codes to know for your website.

  • Intro to coding langauges.
  • HTML vs. CSS
  • Codes to Know
  • And More!
Loading your download form

You're all set!

Click this link to access this resource at any time.

Access now
Learn more

When to Use ID vs. Class

While there’s no hard-and-fast rule for using ID vs. class, the consensus holds that it’s worth using ID for elements that appear once per page — such as headers, footers, or menus — while class is used for elements such as paragraphs, links, and buttons that appear more than once.

As noted above, IDs can be used in conjunction with classes. For example, two button elements might have the same classes to define their basic size and style, but different IDs to determine their position on the page.

Once you’ve added a class to an element, you need to create rule sets for these classes in CSS. “Rule sets” are lines of code that tell a browser how those elements should look on the front end of your website. We can begin creating rule sets using CSS class selectors and declaration blocks. When designing a website, these elements are crucial for creating an engaging user experience.

Lastly, you need to create rule sets for these classes in CSS. We do this using CSS class selectors and declaration blocks.

In our example, we’ll create declaration blocks for both of our CSS classes with the selectors .orange-text and .blue-text:


/* declaration for our first CSS class */
.orange-text {
color: orange;
font-weight: bold;
}

/* declaration for our second CSS class */
.blue-text {
color: blue;
font-weight: bold;
}

When we pair our HTML and CSS together, we see how our CSS classes target certain elements with our custom styling:

See the Pen css class: span example by Christina Perricone (@hubspot) on CodePen.

Note that the class attribute doesn't change the content or style of the HTML document by itself. Meaning, simply adding a class attribute to an element without any CSS will not change the appearance or formatting of the element on the front end. You need to assign CSS rules to the class to see any change.

It also helps to create class names that describe the element in the class. In the above example, we used the names .orange-text and .blue-text because we were creating colorful text. These names are descriptive enough that someone just reading the CSS would understand the purpose of the class.

Class names can be one or multiple words. If your class name is multiple words, use hyphens where you would put spaces. Also, it’s common practice to write class names in lowercase. Some examples of class names include .bright-blue and .fancy-text.

How to Use CSS Classes

Now that we understand what a CSS class is and how it appears in the body section of an HTML file, let's take a look at how to use them. I've designed several websites, and this is my preferred step-by-step process. 

1. Open up your HTML document. 

To use CSS classes, we actually don't start in our CSS code. Open your HTML document first in a code editor or in your website's backend. 

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Beginner's Guide to HTML & CSS

Learn the basic definitions, differences, and codes to know for your website.

  • Intro to coding langauges.
  • HTML vs. CSS
  • Codes to Know
  • And More!
Loading your download form

You're all set!

Click this link to access this resource at any time.

Access now
Learn more

2. Locate or create the element you want to style. 

Next up, find the HTML element you want to style with a unique CSS class. This can be any HTML element, such as buttons, divs, paragraphs, headings, links, tables, and more. 

It also helps to locate the corresponding element in the front-end of your website, so that you can see your changes as you make them.  

3. Add the CSS class declaration to the opening tag of the HTML element. 

This step can technically come at any point in this process, but I personally prefer to add the CSS class to the opening tag right as I'm checking my HTML document. You could skip to the next step, however, and add the class after you're done. 

Here's what that looks like: 

<div class="class-example">This is a div I'd like to style with a CSS class.</div>

<div>This is a div I'll be leaving alone.</div>

4. Open up your CSS file. 

Now, we can access our CSS code. Open up your CSS file in your code editor, or access it in your website's backend.

Alternatively, access the <style></style> tags in the head of your HTML document. 

5. Create the CSS class and its declarations. 

To style your brand new CSS class, add a period (.), then your class name. That should look like this: 

.class-example{

Insert your style declaration between the open brackets. This could be anything from padding to background color to text color. 

Remember to continuously look on the front-end to see how your changes render. 

6. Apply the CSS class to multiple HTML elements. 

If you're happy with your changes, then go back into your HTML code and apply the CSS class to all the elements you'd like to style with these same declarations.

<div class="class-example">This is the first div I'd like to style with my new CSS class.</div>

<div>This is a div I'll be leaving alone.</div>

<div class="class-example">This is the second div I'd like to style with the same CSS class.</div>

Unlike CSS IDs, CSS classes can be used on multiple elements, but keep in mind that you should keep the element type consistent. For instance, if you created a class to style a div, then you should use it on divs only, and not divs and tables, for instance. 

CSS Class Examples & Use Cases

Bootstrap CSS Classes

Many CSS frameworks make heavy use of CSS classes. For instance, Bootstrap CSS uses classes to define page elements.

Let’s see an example of how Bootstrap uses CSS classes. In Bootstrap CSS, the CSS class .btn can be used with the <button> HTML element (as well as the <a> and <input> elements). Bootstrap contains CSS that automatically formats any elements defined with the .btn class a certain way. Therefore, simply adding the attribute class=“btn” to an element changes its appearance.

More precisely, adding the .btn class to an element sets the font and font size, and if a visitor clicks on the button text, an outline of a button with rounded edges appears.

Bootstrap also has classes for styling buttons in other ways, such as background color. If we add the class .btn-success or .btn-danger the button will show as green or red respectively.

See the Pen css class: bootstrap example by Christina Perricone (@hubspot) on CodePen.

With CSS classes, Bootstrap lets us quickly style page elements by just adding one or more class names. CSS classes enable you to format different types of elements while writing less code.

Pseudo-Classes

There's more to see on a web page than HTML content. A great deal of information about the user's activity is transmitted while they interact with the page. Some of this information is a reflection of what they're doing.

Consider a link within your content. The user may or may not interact with it. If they do, you can use pseudo-classes to capture temporary user information such as when they hover, click, and follow the link.

Pseudo-classes are identified by a colon followed by the class. They will appear after a CSS selector with no space in between.

Common pseudo-classes for link styling are:

  • :link targets a link that the user hasn't visited.
  • :visited targets a link that's been visited by the user before.
  • :hover targets a link with the user's cursor over it.
  • :active targets a link that's being pressed down.

Let's look at an example. Say you want to remove the underline from only certain links in all states. Meaning, no matter if the user has visited the link, is hovering over it, or is actively pressing down on it, an underline will not appear below these specific links.

In that case, you'd add a class attribute only to the links you want to remove the underline from. Then, add four rule sets with the class selector and the four respective pseudo-classes. In each declaration block, you'll set the text-decoration property to none.

See the Pen css class: pseudo classes by Christina Perricone (@hubspot) on CodePen.

Descendant Selectors

The goal of CSS classes is to apply formatting to specific elements. To that end, descendant selectors are a great addition to your toolbox.

Descendant selectors let you target elements inside of other elements. For instance, you may have already created a class to define a general style for paragraph or heading text, but want certain words within the paragraph to be styled in their own way.

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Beginner's Guide to HTML & CSS

Learn the basic definitions, differences, and codes to know for your website.

  • Intro to coding langauges.
  • HTML vs. CSS
  • Codes to Know
  • And More!
Loading your download form

You're all set!

Click this link to access this resource at any time.

Access now
Learn more

Descendant selectors allow you to add these special styles to specific words without affecting the surrounding text or changing your HTML document.

Let's say you apply the .blue-text class to a heading, but want to change the color of a word within the heading. Wrap the word in a span element, then add another ruleset with a descendent selector: After the CSS class selector .blue-text, add a space and then the type selector span.

See the Pen css class: descendant selector example by Christina Perricone (@hubspot) on CodePen.

Be careful not to overdo this, though. Overuse of descendant selectors can lead you to set up confusing rules that will make changes difficult for you down the line.

While you can have multiple instances of a class on an HTML page, you can only have one instance of a CSS ID on a page. To give an element an ID, add the attribute id=“name” to its opening tag, and replace name with a unique identifying name. In the CSS, the corresponding ID selector begins with a pound sign (#) instead of a period.

Additionally, ID attributes provide the target for URL fragments (such as page anchors), so they should be unique. Fragments help you refer a user to a specific part of a web page — the fragment looks like an ID selector placed at the end of the URL.

The fragment looks like a CSS ID selector placed at the end of the URL

Image Source

CSS Specificity

Sometimes, CSS rules conflict. For example, if multiple selectors target the same element in a document, which rules apply? This is determined by CSS specificity. In CSS, different selectors have varying weights. When two or more rules conflict on the same element, the more specific one applies.

This is how the different selectors rank in the specificity hierarchy:

  1. Inline CSS: Inline CSS appears as style attributes in the opening tag of HTML elements. Since this CSS is closest to the HTML, it has the highest level of specificity.
  2. ID selectors: An ID is unique to a page element and thus, very specific.
  3. Class selectors, attribute selectors, and pseudo-class selectors: These three selector types have equal specificity. If all three types are applied to the same HTML element, the one appearing latest in the stylesheet will apply and override the rest.
  4. Type selectors: These select all HTML elements that have a given node name and have the syntax element. These are element names and pseudo-elements.

This is where ID selectors shine. Because they're so specific, almost any other type of selector that goes up against them loses. On the other hand, the universal selector (*) will lose every time because of its low specificity.

Sometimes, after applying a CSS class to a range of elements, you might want to override the declarations for a specific element on the page. Let’s go over how you can easily do that.

How to Override CSS Class

Looking to override a CSS class? Here’s how.

Determine the class you want to override.

First, pinpoint the class you want to override, and specifically the rule you want to change. This could be font color, size, positioning, etc. The class itself doesn’t matter so much as identifying where the class is and how it’s related to elements around it. Ideally, you want to cause minimal CSS disruption when you carry out the override.

Create a more specific declaration.

The basic rule of thumb when it comes to two conflicting classes is that the one with the more specific declaration wins out. For example, ID selectors are more specific than class selectors, and class selectors are more specific than type selectors.

In practice, this means that adding a class selector to an element with only a type selector will override the current class, while adding an ID selector will override any competing class or type selector.

Alternatively, use the !important declaration.

You can also use the !important declaration as a shortcut to override CSS class. In CSS, !important means exactly that — that the following directive is important and must be applied. When placed at the end of a declaration, !important will take precedence over other classes. Click here to learn more about what this looks like.

The caveat? This declaration effectively breaks the natural cascading function of CSS, in turn making your code harder to debug, so it’s best used sparingly.

Start Using CSS Classes

CSS classes help you customize elements on a web page faster and more easily. Using CSS class selectors allows you to set up rules to format entire classes of HTML elements, specific elements in a class, or single elements across many classes. You can be as creative as you want when designing your site, but remember the goal is to improve your website's user experience.

Editor's note: This post was originally published in February 2020 and has been updated for comprehensiveness.

New Call-to-action

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Dozens of free coding templates you can start using right now.

CMS Hub is flexible for marketers, powerful for developers, and gives customers a personalized, secure experience

START FREE OR GET A DEMO