Benedict's Blog

Technical Blog - CSS Concepts
Back to Home

Technical Blog - CSS Concepts

What are the best practices associated with using classes vs. ids?

    The two most commonly used CSS selectors are : classes and ids. They are used to find a specific element that we want to style from an HTML file.

    Classes use the period/dot '.' character to select a specific element.

    In CSS file: when want to create a custom div element named blog-post, we write div.blog-post or .blogpost.

    In HTML file: when we want to use our custom div element named blog-post, we write: <div class="blog-post">.

    Classes are the preferred CSS selector when styling multiple elements with a shared characteristic

    For example, if we want text with different colours then we can create several classes for each:

    text.red { color: red; } and <text class="red"> gives red text.

    text.green { color: green; } and <text class="green"> gives green text.

    text.blue { color: blue; } and <text class="blue"> gives blue text.

    Ids use the hash '#' notation next to a specific element.

    In CSS file: when we want to create a custom div element named nav-bar, we write div#nav-bar or #nav-bar.

    In HTML file: we declare an id inside a tag like this: <div id="nav-bar">.

    Unlike class names which can be used by several elements, an id can only be used by one HTML element.

    An example of an id being used to style a div element can be seen below:

    In CSS:
    #customText {
                      background-color: yellow;
                      color: red;
                      }
                      

    In HTML: text id="customText">

    Web View: Custom Text

    The id of an element is unique within a page, so apart from CSS styling the id can also be used as a selector to select one unique element for things like JavaScript.