CSS Selectors and Specificity

What are CSS Selectors?

CSS selectors are used to select HTML elements on the page that you want to style. There are different types of selectors, including:

1. Element Selectors

These target HTML tags directly. For example, p targets all paragraph elements.

p { color: red; }

2. Class Selectors

These target elements with a specific class attribute. Class selectors are prefixed with a ..

.example { color: blue; }

3. ID Selectors

These target elements with a specific ID attribute. ID selectors are prefixed with a #.

#unique { color: green; }

4. Universal Selector

The universal selector targets all elements on the page. It is represented by *.

* { margin: 0; padding: 0; }

5. Attribute Selectors

These target elements based on their attributes. For example, to target links with the href attribute:

a[href] { color: orange; }

6. Pseudo-class Selectors

These select elements based on their state or position. For example, :hover targets an element when the user hovers over it.

a:hover { color: purple; }

7. Pseudo-element Selectors

These allow you to style part of an element. For example, ::before adds content before an element.

p::before { content: "Prefix: "; }

CSS Specificity

Specificity is how the browser decides which styles to apply when multiple CSS rules match the same element. The more specific a selector, the higher its priority.

How Specificity Works:

Example of Specificity:

This box will be styled based on CSS specificity.

The color of the text below will depend on which CSS rule has higher specificity.

Example Styles (Order of application):


            /* Style 1: Element selector */
            div {
                color: yellow;
            }
            
            /* Style 2: ID selector */
            #test {
                color: red;
            }
            
            /* Style 3: Class selector */
            .selector-box {
                color: blue;
            }
        

The final color of the text in the box will be red because the ID selector has higher specificity than the class and element selectors.

Quiz: Test Your Knowledge

1. Which CSS selector targets an element with a specific class?




2. Which selector has the highest specificity?




3. What happens when two CSS rules with the same specificity conflict?