CSS Selectors Demo

Types of CSS Selectors

1. Element Selectors

Element selectors target HTML elements directly by their tag name. For example, this paragraph is styled using the p element selector.

This div is styled using the div element selector.

The CSS code for element selectors looks like:

h1 {
    color: blue;
    text-align: center;
}

p {
    font-family: Arial, sans-serif;
    line-height: 1.5;
}

div {
    padding: 10px;
    margin-bottom: 20px;
    border: 1px solid #ddd;
}
            

2. ID Selectors

ID selectors target unique elements with a specific ID attribute. IDs must be unique - you can only use each ID once per page.

This div has id="unique-element" and is styled using the #unique-element ID selector.

This heading has id="special-heading"

The CSS code for ID selectors looks like:

#unique-element {
    background-color: #ffeb3b;
    font-weight: bold;
    padding: 15px;
    border: 2px dashed black;
}

#special-heading {
    color: purple;
    font-style: italic;
    text-shadow: 1px 1px 2px #aaa;
}
            

3. Class Selectors

Class selectors target elements with a specific class attribute. Multiple elements can share the same class.

This paragraph has class="highlight" and is styled using the .highlight class selector.

This div has class="box" and is styled using the .box class selector.

This is another paragraph with class="highlight" - both get the same styling.

This heading has class="text-center"

The CSS code for class selectors looks like:

.highlight {
    background-color: #e6f7ff;
    border-left: 4px solid #1890ff;
    padding-left: 10px;
}

.box {
    background-color: #f5f5f5;
    border-radius: 5px;
    padding: 15px;
}

.text-center {
    text-align: center;
}
            

4. Combined Selectors

This paragraph has class="note" and is targeted by the p.note combined selector.

This div also has class="note" but won't be affected by the p.note selector.

This h2 is inside an element with id="container"

The CSS code for combined selectors looks like:

p.note {
    font-style: italic;
    color: #888;
    font-size: 0.9em;
}

#container h2 {
    color: green;
    border-bottom: 1px solid green;
}
            

5. Multiple Classes

HTML elements can have multiple classes:

This div has both class="box" and class="highlight" so it gets styles from both class definitions.

The HTML for multiple classes looks like:

<div class="box highlight">...</div>

Selector Specificity (Which Rule Wins)

When multiple rules apply to the same element, specificity determines which one wins:

  1. ID selectors (#example): Highest specificity
  2. Class selectors (.example): Medium specificity
  3. Element selectors (p, div): Lowest specificity

A more specific selector will override a less specific one for the same property.