CSS Tutorial



CSS SELECTORS


CSS Selectors

CSS selectors are patterns used to select and style HTML elements. They are the foundation of CSS, as they determine which elements will be styled and how.

There are several types of CSS selectors, ranging from simple to complex, and each type has a specific use case for targeting HTML elements.

Types of CSS Selectors:

  • Universal Selector: * targets all elements on the page.
  • Type Selector (Element Selector): Targets elements by their HTML tag name, like div, p, h1.
  • Class Selector: Targets elements by their class attribute, using a period (.) followed by the class name, like .example.
  • ID Selector: Targets elements by their ID attribute, using a hash (#) followed by the ID name, like #header.
  • Attribute Selector: Targets elements based on their attributes, like [type="text"].
  • Descendant Selector: Targets elements nested inside another element, separated by a space, like div p.
  • Child Selector: Targets elements that are direct children of another element, using >, like div > p.
  • Pseudo-class Selector: Targets elements based on their state, like :hover.
  • Pseudo-element Selector: Targets specific parts of an element, like ::before or ::after.

Example: Using Selectors

Here’s an example demonstrating different CSS selectors:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
          /* Type Selector */
          p {
            color: blue;
          }

          /* Class Selector */
          .highlight {
            font-weight: bold;
          }

          /* ID Selector */
          #intro {
            font-size: 18px;
          }

          /* Descendant Selector */
          div p {
            color: green;
          }

          /* Child Selector */
          div > p {
            font-style: italic;
          }

          /* Pseudo-class Selector */
          a:hover {
            color: red;
          }

          /* Pseudo-element Selector */
          p::before {
            content: "Note: ";
            font-weight: bold;
          }
        </style>
      </head>
      <body>

        <div>
          <p id="intro">This is an introductory paragraph.</p>
          <p class="highlight">This is a highlighted paragraph.</p>
          <a href="#">Hover over this link</a>
        </div>

      </body>
    </html>
  

Output:

This is an introductory paragraph.

This is a highlighted paragraph.

Hover over this link

In this example, different selectors are used to target and style specific elements on the page.

Conclusion

CSS selectors are crucial for styling elements on a web page. Understanding the various types of selectors and their applications will help you write more efficient and effective CSS code.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review