CSS Selectors

CSS selectors are the part of CSS rulesets that determine which elements in the document tree are styled by the CSS declarations that follow. A selector points to the HTML element you want to style. 

Code Example using CSS selectors

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Selector Example</title>
    <style>
        /* Universal Selector */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* Type Selector */
        section {
            margin: 20px;
            padding: 20px;
            background-color: #f4f4f4;
        }

        /* Class Selector */
        .highlight {
            background-color: yellow;
        }

        /* ID Selector */
        #main {
            padding: 20px;
            background-color: #e9ecef;
            border: 1px solid #ccc;
        }

        /* Descendant Selector */
        #main p {
            font-size: 16px;
            line-height: 1.5;
        }

        /* Child Selector */
        #main > h1 {
            font-size: 24px;
            color: darkblue;
        }

        /* Adjacent Sibling Selector */
        h1 + p {
            color: red;
        }

        /* General Sibling Selector */
        h1 ~ p {
            margin-top: 20px;
        }

        /* Attribute Selector */
        input[type="text"] {
            padding: 10px;
            margin: 10px 0;
            display: block;
        }

        /* Pseudo-class */
        p:first-child {
            color: green;
        }

        /* Pseudo-element */
        p::first-letter {
            font-size: 200%;
            color: blue;
        }
    </style>
</head>
<body>
    <section id="main">
        <h1>Welcome to Our Website</h1>
        <p>This paragraph is styled red because it immediately follows the h1.</p>
        <p class="highlight">This is highlighted in yellow because of its class.</p>
        <p>Notice the first letter of this sentence is styled differently.</p>
    </section>
    <input type="text" placeholder="Type here...">
</body>
</html>

Types of CSS Selectors

Universal Selector

  • *: Targets all elements within the document.

Type Selector

  • <elementname>: Targets all elements of the specified node name.

Class Selector

  • .classname: Targets all elements with the specific class attribute.

ID Selector

  • #idname: Targets the element with the specific ID.

Descendant Selector

  • A B: Targets all B elements that are descendants of A.

Child Selector

  • A > B: Targets all B elements that are direct children of A.

Adjacent Sibling Selector

  • A + B: Targets a B element immediately following A.

General Sibling Selector

  • A ~ B: Targets all B elements that follow A.

Attribute Selector

  • [attr]: Targets elements with the attribute attr.
  • [attr=value]: Targets elements with the attribute attr matching the exact value.
  • [attr^=value]: Targets elements with the attribute attr starting with value.
  • [attr$=value]: Targets elements with the attribute attr ending with value.
  • [attr*=value]: Targets elements with the attribute attr containing value.
  • [attr|=value]: Targets elements with the attribute attr with a hyphen-separated list starting with value.
  • [attr~=value]: Targets elements with the attribute attr containing the word value.

Pseudo-classes

  • :active: Targets the active link.
  • :checked: Targets every checked <input> element.
  • :disabled: Targets every disabled element.
  • :empty: Targets elements that have no children.
  • :enabled: Targets every enabled element.
  • :first-child: Targets the first child of every element.
  • :first-of-type: Targets the first element of its type.
  • :focus: Targets the element that has focus.
  • :hover: Targets links on mouse-over.
  • :in-range: Targets input elements with a value within a specified range.
  • :invalid: Targets all elements with an invalid value.
  • :last-child: Targets the last child of every element.
  • :last-of-type: Targets the last element of its type.
  • :link: Targets all unvisited links.
  • :not(selector): Targets every element that is not a selector.
  • :nth-child(n): Targets the nth (e.g., 1st, 3rd, 12th) child of every element.
  • :nth-last-child(n): Targets the nth-last child of every element.
  • :nth-of-type(n): Targets the nth of its type of every element.
  • :nth-last-of-type(n): Targets the nth-last of its type of every element.
  • :only-of-type: Targets every element that is the only child of its type.
  • :only-child: Targets every element that is the only child of its parent.
  • :optional: Targets input elements with no "required" attribute.
  • :out-of-range: Targets input elements with a value out of a specified range.
  • :read-only: Targets elements which are "readonly".
  • :read-write: Targets elements which are not "readonly".
  • :required: Targets elements with a "required" attribute.
  • :root: Targets the document's root element.
  • :target: Targets the current active #id element (clicked on a URL containing that anchor name).
  • :valid: Targets all elements with a valid value.
  • :visited: Targets all visited links.

Pseudo-elements

  • ::after: Insert something after the content of each selected element.
  • ::before: Insert something before the content of each selected element.
  • ::first-letter: Targets the first letter of every selected element.
  • ::first-line: Targets the first line of every selected element.
  • ::selection: Targets the portion of an element that is selected by a user.

FAQs about CSS selectors

1. What is the difference between Class and ID selectors?

  • Class Selector (.classname): Targets all elements that have the specified class attribute. It's useful for applying styles to multiple elements without affecting others not tagged with that class.
  • ID Selector (#idname): Targets the element with the specific ID. The ID should be unique within a page, used to select one unique element.

2. When should I use :nth-child() vs. :nth-of-type()?

  • :nth-child(n): Selects the nth child, regardless of type. This is useful when you want to style elements based on their order regardless of their parent's type.
  • :nth-of-type(n): Selects the nth child of its type (like the nth <p> or <div>), which is practical for more specific structures where only elements of the same type are considered.

3. Can CSS selectors target attributes of elements?

  • Yes, attribute selectors like [type="text"], [name^="user"] enable you to style elements based on their attributes, offering a powerful way to apply styles dynamically based on element attributes.

4. How does the Universal Selector (*) differ from the Descendant Selector ( )?

  • Universal Selector (*): Targets all elements in the HTML document. It's often used for broad resets like setting margins and paddings to zero.
  • Descendant Selector ( ): Places a space between two selectors, targeting elements that are nested within specified parent elements regardless of depth (e.g., div p would target all <p> tags inside <div> tags).

5. What are pseudo-classes and pseudo-elements?

  • Pseudo-classes (:hover, :focus, etc.): Define styles in relation to the state of an element. For example, :hover applies when the user points a mouse over an element.
  • Pseudo-elements (::before, ::after): Used to style specified parts of an element, such as inserting content before or styling the first letter of a text block.

6. What is the importance of specificity in CSS selectors?

  • Specificity determines which styles are applied when one element is targeted by multiple rules. It calculates which selector is more specific and therefore which rule should be applied. For example, id selectors have higher specificity than class selectors and type selectors.
tools

Computer Science

Related Articles