Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

CSS Class Selector: A Deep Dive To Successful Styling Precision

In CSS, selectors are crucial for enhancing the visual layout of a webpage. Selectors specify rules that determine the styles that apply to elements in the document tree. Like other selectors, class selectors also play a vital role in styling specific HTML elements. It provides a way to apply unique styles to achieve a beautiful user interface. Most importantly, multiple elements can have the same class name, making it possible to target these elements .

In addition, CSS3 introduced new selectors, creating new possibilities and ways to improve existing practices. Some of these selectors work very well with the class selector to target specific HTML elements.

This article will discuss the fundamentals of CSS class selectors and explore more complex styling by combining a class selector with new CSS3 selectors. To further streamline your projects, check out the purecode.ai marketplace, where you can access over 10,000 AI-generated ready-made templates and components for your next endeavor.

Understanding CSS Class?

In HTML, elements incorporate the class attribute that receives a list of class names separated by spaces. Classes allow CSS to select HTML elements with the class selector and apply unique styles to these elements.

When defining a class selector, the period “.” symbol precedes the class name to select the desired class. The syntax is as follows:

HTML

<p class="some-class"></p>
CSS

.some-class {
  
}

Classes are a good option for practicing the Don’t Repeat Yourself (DRY) principle because they can be applied to multiple tags, making them reusable. The class makes it possible to style a single HTML element differently from other elements with the same class name by adding another class name after a previously defined class. Consider the following:

HTML

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Styling a single HTML element differently from other elements</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <section class="container">
      <div class="box blue"></div>
      <div class="box blue cyan"></div>
      <div class="box blue"></div>
      <div class="box blue"></div>
      <div class="box blue"></div>
    </section>
  </body>
</html>
style.css

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 24px;
  height: 100vh;
}

.box {
  height: 50px;
  width: 50px;
  border: 1px solid #ccc;
}

.blue {
  background-color: blue;
}

.cyan {
  background-color: cyan;
}

Output:

A visual representation of targeting a single HTML element with a class selector.

From the example above, we targeted and styled the div element with the “cyan” class name differently from the other boxes.

In the next section, we will look at the HTML elements that support the class attribute.

Element Support for the Class Attribute

The class attribute is versatile to a variety of HTML elements. An HTML element capable of being styled can utilize the class attribute; this means virtually most elements except the <head> tag and all tags within it. These HTML elements include the following:

  1. Text-based elements:

    • paragraph (<p>)

    • headings (<h1>, <h2>, <h3> etc.)

    • <strong>, <em>

  2. Inline elements: these elements include: <a>, <abbr>, etc

  3. Semantic elements:

    • Navigation elements: <nav>, <aside>, etc

    • Containers: <main>, <section>, <article>, <figure>, <fieldset>, etc

    • others: <footer>, <header>, <body>, etc

  4. Form elements:

    • <form>, <input>, <select>, <textarea>, etc

  5. interactive elements:

    • <button>, <a>, <label>, etc

  6. Table elements:

    • <table>, <thead>, <tbody>, <tr>, <th>, <td>, etc

  7. Media elements:

    • <img>, <audio>, <video>, etc

  8. List elements:

    • <ul>, <ol>, <li>, etc

Although these are not all the HTML elements that support the class attribute, they are the major elements.

Usage of CSS Class

A CSS class selector together with a class name can be used to target a specific class attribute in HTML. Below is a breakdown of how to use the CSS class.

Steps To Use The CSS Class

These steps include the following:

  1. Create an HTML document and add the element to be styled:

    <!doctype html> <html lang="en">   <head>     <meta charset="UTF-8" />     <meta name="viewport" content="width=device-width, initial-scale=1.0" />     <meta http-equiv="X-UA-Compatible" content="ie=edge" />     <title>Using a CSS class</title>     <link href="./style.css" rel="stylesheet" />   </head>   <body>     <header class="first-header">       <h3>Using a CSS class</h3>       <p>Lorem ipsum dolor sit amet, consectetur adipisicing.</p>     </header>   </body> </html>

    Output:

  1. Define the class in CSS

    style.css
    
    .first-header {
      
    }
  2. Apply styles with the class name

    style.css .first-header {   text-align: center; } .first-header h3 {   font-size: 32px;   color: #333; } .first-header p {   font-size: 18px;   color: #1d1e1e; }

    Output:

From the example above, we created a container element and assigned the class name first-header to the class attribute. We used the class selector in the CSS stylesheet to target and style all elements with the class name first-header and its children.

Distinguishing Class Selector and ID Selector

HTML and CSS use ID and class to define and style elements. Although ID and class provide an effective way to maintain a readable and efficient codebase, they differ in how they operate. These differences include the following:

ID SelectorsClass Selectors
IDs are unique. That is only one ID per element can be on a page.Classes are not unique. One class can be shared across multiple elements.
IDs can be used together with the hash value as a browser jump link to locate another element on the same page.Class has no such browser functionality.
It is typically used in JavaScript to target and assign functionality to a specific element on a pageIt is used in JavaScript to select and assign functionality to a group of elements.
In CSS, the ID selector is preceded by a hash symbol.In CSS, the class selector is declared with a preceding period symbol.

To learn more about ID, check out the MDN docs on the ID selector and ID attribute.

Best Practices for CSS Class

Proper application of CSS class is crucial for a functional, scalable, and well-organized codebase. The convention for naming CSS classes improves clarity, reusability, and flexibility within a codebase. This section will discuss the CSS class best practices crucial to the development process.

The following are the best practices to consider while using a CSS class:

  • Use semantic class naming

  • Use descriptive names

  • Use short and simple names

  • Consistent naming convention

  • BEM convention

Use Semantic Class Naming

Choosing class names that align with an element’s intended function or purpose is crucial. Semantic class names provide meaning to an element’s content and structure. This practice enhances the readability and clarity of the code.

Use Descriptive Names

Class names should be descriptive enough to convey the element’s purpose. Rather than using vague or generic names, choose more meaningful and explicit names that reflect the element’s role within the document. For example, submit-btnhero-content, etc, provide more context and clarity than btn or content.

Use Short And Simple Names: 

While descriptive and distinct names are essential, avoid making them complex and wordy. Aim for brief and concise class names that improve readability and maintainability. For example, hero, nav, container, etc.

Consistent Naming Convention

Adopting and adhering to a consistent naming convention across all projects is essential. Popular conventions include Block Element Modifier (BEM), Scalable and Modular Architecture for CSS (SMACSS), and Object-Oriented CSS (OOCSS) with BEM and OOCSS being the preferred options.

BEM Convention

BEM provides a structured and modular way of naming classes that reflects the HTML structure. BEM consists of a Block (standalone elements), Elements (bits that make up a block), and Modifiers (changes the appearance of the block or elements). The BEM convention includes the following patterns: .block, .block__element, .block–modifier. Below is an example that uses the BEM convention:

/* BEM Naming Convention example */

/* Block */
.header {} 

/* Element of the block */
.header__logo {} 
.header__menu {}

/* Modifier of the element */
.header__menu--active {} 

To learn more about the best practices for CSS class, check the tutorial video below:

Exploring CSS Class With Complex Selectors

Despite the usefulness of CSS classes, the tendency to create excessive and unnecessary classes and HTML elements remains apparent. The best way to maintain clean and semantic markup and styles is to combine CSS class with intricate CSS selectors that directly select HTML elements, eliminating the necessity for class name pollution in both markup and stylesheet.

This section will explore some complex CSS selectors.

Pseudo-elements

Pseudo-elements are CSS selectors that allow unique parts of an element to be styled. A double colon, “::”, precedes the selector. These selectors include the following:

  • First line and First letter

  • Before and After

First line and first letter pseudo-elements

The ::first-line pseudo-element is used to style the first line of a paragraph. Whereas the ::first-letter pseudo-element matches and styles the first letter of a paragraph. The syntax is as follows:

.some-paragraph::first-line {

} 

.some-paragraph::first-letter {

}

Before and After pseudo-elements

The ::before and ::after pseudo-elements are used together with the content property to insert new inline-level pseudo-elements into the selected element. Below is a syntax representing these selectors:

.some-elem::before {}

.some-elem::after {}

CSS Attribute selector

The attribute selectors allow you to select and style HTML elements based on their attributes or attribute values. The different types of attribute selectors include:

  • [attribute] selector

  • [attribute=value] selector

  • [attribute~=”value”] selector

  • [attribute*=”value”] selector

  • [attribute^=”value”] selector

  • [attribute$=”value”] selector

[attribute] selector

These attribute selectors select an element if it includes the specified attribute, regardless of a value. The following is the syntax for the [attribute] selector:

element[attribute] {}

[attribute=value] selector

This attribute selector matches all the HTML elements whose target attribute has the specified value. Consider the following example:

input[name="artist"] {}

The selector from this example will select all the HTML elements whose name attribute has the value of artist.

[attribute~=”value”] selector

This selector targets HTML elements containing an attribute with the exact specified value. Below is an example of the attribute spaced selector:

a.nav-link[href~="https://www.artist.com"] {}

[attribute*=”value”] selector

This selector selects elements that match the substring value assigned to the specified attribute. The selector is also known as Attribute Contains Substring Selector. Below is the code example:

.row > [class*="col-"] {}

[attribute^=”value”] selector

This selector selects elements whose target attribute begins with the specified value. For example:

p[class^="some-class"] {}

[attribute$=”value”] selector

This selector selects elements whose target attribute ends with the specified value. For example:

p[class$="some-class"] {}

Check this article to achieve more powerful styling with CSS attribute selector.

Child Selectors

The child selector, represented by the sign “>“, is very effective at adding a bit of specificity to select HTML elements that are direct descendants of a parent element. It includes the following syntax:

.parent_class > child_element

The child combinator confines descendant styling to match only the direct descendants of a particular HTML element. Let’s consider the following code example:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Example using a child selector</title>
    <style>
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 24px;
        height: 100vh;
      }

      .container > div {
        height: 50px;
        width: 50px;
        border: 2px solid blue;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .inner {
        height: 25px;
        width: 25px;
      }
    </style>
  </head>
  <body>
    <section class="container">
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
    </section>
  </body>
</html>

Output:

A visual representation of styling divs within a container with a child selector.

Descendant Selectors

The descendant selectors let you target all descendants of a specified element. The descendant selectors provide a way to add styles to all the HTML elements within a container or parent element. Below is the code syntax for using the descendant selector with a CSS class selector:

.parent_class descendant_element

The example below shows how to use the descendant selector with a class selector:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Example using a descendant selector</title>
    <style>
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 24px;
        height: 100vh;
      }

      .container > div {
        height: 50px;
        width: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .container div {
        border: 2px solid blue;
      }

      .inner {
        height: 25px;
        width: 25px;
      }
    </style>
  </head>
  <body>
    <section class="container">
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
      <div>
        <div class="inner"></div>
      </div>
    </section>
  </body>
</html>

Output:

A visual representation of using the descendant selector to target 10 of the same HTML element within a container

In The example above, the immediate descendant of the HTML element with the “container” class and its nested progeny have distinct dimensions of fixed width and height. Ultimately, the descendant selector was employed to add a blue border to all descendants associated with the element featuring the “container” class.

Pseudo-class Selectors

These selectors are context-dependent. They select an HTML element based on the state and context of that element. To create a pseudo-class selector, prefixed the class with a colon, “:“. These selectors should appear after a CSS selector. Pseudo-class selectors consist of the following types:

  • Dynamic pseudo-classes

  • Structural pseudo-classes

  • Language pseudo-class

  • Functional pseudo-classes

Dynamic Pseudo-classes

These selectors do not exist in the Document Object Model (DOM) on the initial render. They only become available when the user interacts with the user interface. They include the following:

  • :link applies to an unvisited link. 

  • :visited selects a link that the user visited.

  • :hover targets a link when the user’s cursor moves over it.

  • :active targets a link that the user pressed down.

  • :focus applies when an interactive HTML element is in focus.

  • :disabled select disabled inputs.

Structural Pseudo-classes

These selectors deal with the order of HTML elements. They include the following:

  • :nth-child() applies to one or more children of a parent element.

  • :first-child() applies to the first child of a parent element.

  • :last-child() targets the last child of a parent element.

  • :only-child() targets the only child of a parent element.

  • :nth-of-type() applies to one or more children of the same type as its parent element.

  • :first-of-type() applies to the first child of the same type as its parent element.

  • :last-of-type() targets the last child of the same type as its parent element.

  • :only-of-type() matches the only child of the same type as its parent element.

Consider the following example:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Code Example</title>
    <style>
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 24px;
        height: 100vh;
      }

      .container > div {
        height: 50px;
        width: 50px;
        display: flex;
        background-color: #ccc;
      }

      .container > div:first-child {
        background-color: blue;
      }

      .container > div:nth-child(even) {
        background-color: rgb(54, 27, 146);
      }

      .container > div:last-child {
        background-color: rgb(20, 155, 124);
      }
    </style>
  </head>
  <body>
    <section class="container">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </section>
  </body>
</html>

Output:

A visual representation of the specificity of  the structural pseudo-class

Language Pseudo-class

This selector, :lang(), allows you to select an HTML element based on its language.

Functional Pseudo-classes

These selectors match elements that meet certain conditions based on the selector list passed as parameters. Examples include the following:

  • :has() selects elements that contain a content or child selector.

  • :is() selects elements that match any selector provided with the specificity of the most specific selector.

  • :where() selects elements that match any selector provided with zero specificity.

  • :not() selects all elements except those matching the provided selectors.

Overriding CSS Class Styles

Overriding a CSS class selector is a common and useful practice when attempting to change the predefined styles of an element. The following subsections discuss how to achieve this.

Using CSS specificity

In CSS, counting the number of inline styles, ID selectors, class selectors, and element selectors an element contains determines its specificity. In conflicting class styles, CSS class declarations with higher specificity take precedence over the class selectors with lower specificity.

Consider the following examples:

.some_class {

}

.parent_elem .some_class {

}

.some_class.another_class {

}

These are three different class declarations. The second class declaration applies to an HTML element with the class name “.some_class” as a descendent of the element with the class name “.parent_class.” The last class selector also targets elements with “some_class” and “another_class” class names. However, the second and latter selectors have the same cascading value because they both have two class selectors. But the last declaration will override the second because it was declared last in the source order. Check the following article, to learn more about CSS specificity.

Using Inline Styles

Inline styles are style rules written within the style attribute of an HTML element. Based on the order of specificity, inline styles have the highest and will override both external and internal styles. The following code syntax is an example of inline styling:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Inline styling</title>
    <style>
      .container > div {
        height: 250px;
        width: 250px;
        border: 1px solid red;
      }
    </style>
  </head>
  <body>
    <section class="container">
      <div
        style="height: 100px; width: 100px; border: 1px solid blueviolet"
      ></div>
    </section>
  </body>
</html>
A visual representation of overriding a CSS style declaration with inline styling.

From the image above, none of the styles in the CSS declaration within the style tag were applied, because the inline style overrode them.

Using the !important Declaration

The !important declaration gives a rule the highest priority. In CSS, using !important lets the browser know that the style directive it supersede is vital and must be applied regardless of specificity. The syntax is as follows:

.important-text {
  color: purple !important;
}

Using Media Queries

Media queries provide a way to apply CSS styles that target specific browser characteristics, features, and other user preferences. Depending on the conditions, CSS styles within media queries will override those outside of the media queries. Below is a code example to illustrate the overriding capabilities of media query:

Markup

<body>
    <section class="container">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </section>
</body>
CSS stylesheet

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 24px;
  height: 100vh;
  flex-direction: column;
}

.container > div {
  height: 150px;
  width: 150px;
  background-color: rgb(46, 173, 46);
}

@media only screen and (min-width: 768px) {
  .container {
    flex-direction: row;
  }

  .container > div {
    width: 50px;
    height: 50px;
    background-color: rgb(138, 53, 216);
  }
}

Output:

From the code above, as the browser viewport width changes, the width, height, and background-color properties of the div elements change to the values specified within the media query.

Final notes

In this article, we delved into the fundamentals of CSS class selectors and progressed toward more complex concepts. This concept explores refining the styling precision of a CSS class selector in combination with complex selectors. These selectors give you greater control and flexibility when styling elements on a web page. Combining classes with complex selectors ensures precise and dynamic styles. We also explored ways to override a class style depending on the project requirements.

Based on your current understanding, it’s evident that the significance of CSS class selectors in improving the visual layout and user experience cannot be over-emphasized. Now, it’s your turn to apply this knowledge and create something magical.

Visit us at purecode.ai to quickly craft more flexible and enchanting layouts.

Recommended articles

If you enjoyed this article, consider reading other articles from our blog to improve your understanding of CSS:

Ofili Chukwuemeka Timothy

Ofili Chukwuemeka Timothy