Skip to content

CSS Selectors for Beginners: Basics of Selecting HTML Elements

Posted on:April 9, 2023 at 11:00 AM

CSS selectors are an essential part of styling web pages. They allow you to target specific HTML elements and apply styles to them. In this article, we will cover the basic types of selectors in CSS that every beginner should know.

  1. Element Selectors: Element selectors target specific HTML elements. They are represented by the element name, such as p, h1, or div. To apply styles to all instances of an element, simply use the element selector followed by the desired properties. For example, the following CSS code applies a blue color to all paragraphs on the page:

    p {
      color: blue;
    }
  2. Class Selectors: Class selectors target HTML elements that have a specific class attribute. They are represented by a period (.) followed by the class name. For example, if you have a class named “my-class”, you can apply styles to all elements with that class using the following code:

    .my-class {
      font-size: 20px;
      color: red;
    }

    To apply the class to an HTML element, add the class name within the class attribute, like this:

    <p class="my-class">This paragraph will be styled with the my-class styles</p>
  3. ID Selectors: ID selectors target HTML elements that have a specific ID attribute. They are represented by a hashtag (#) followed by the ID name. For example, if you have an ID named “my-id”, you can apply styles to the element with that ID using the following code:

    #my-id {
      background-color: yellow;
    }

    To apply the ID to an HTML element, add the ID name within the id attribute, like this:

    <div id="my-id">This div will be styled with the my-id styles</div>

    Note that IDs should be unique on a page, meaning that only one element should have a specific ID.

  4. Universal Selectors: Universal selectors target all HTML elements on the page. They are represented by an asterisk (*) symbol. For example, the following CSS code applies a blue color to all elements:

    * {
      color: blue;
    }

    While this can be useful in some cases, it is generally not recommended to use universal selectors since they can negatively impact performance.

Conclusion

These four types of selectors are the basics you need to get started with CSS. Understanding how each one works and when to use them will help you create beautiful and responsive web pages.

What’s next?

In the coming article, we will be covering the Hierarchy of CSS selectors. Don’t forget to follow and share this with your friends that are just starting their web development journey