Breaking News

CSS SELECTORS

CSS Selectors

CSS selectors are used to select HTML elements that you want to style. They tell the browser which elements the CSS rules should apply to.

Types of CSS Selectors

1. Element (Tag) Selector

Selects all HTML elements of a specific type.

CSS:

p {
    color: blue;
}

HTML:

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

Output: Both paragraphs will appear in blue.


2. ID Selector (#)

Selects a single HTML element with a specific id.

CSS:

#heading {
    color: red;
}

HTML:

<h1 id="heading">Welcome to CSS</h1>

Output: The heading will appear in red.

Note: An id should be unique and used only once on a page.


3. Class Selector (.)

Selects all elements with a specific class.

CSS:

.highlight {
    background-color: yellow;
}

HTML:

<p class="highlight">Important text.</p>
<p class="highlight">Another important text.</p>

Output: Both paragraphs will have a yellow background.


4. Universal Selector (*)

Selects all elements on the page.

CSS:

* {
    margin: 0;
    padding: 0;
}

Output: Removes the default margin and padding from all elements.


5. Group Selector (,)

Applies the same style to multiple elements.

CSS:

h1, h2, p {
    font-family: Arial, sans-serif;
}

Output: All <h1>, <h2>, and <p> elements use the Arial font.


Common CSS Selectors

Selector  Example  Description
Element p  Selects all <p> elements
ID #header  Selects the element with id="header"
Class .menu  Selects all elements with class="menu"
Universal *    Selects all elements
Group h1, p  Selects multiple elements

Complete Example

HTML:

<!DOCTYPE html>
<html>
<head>
    <style>
        h1 {
            color: blue;
        }

        .note {
            color: green;
        }

        #title {
            background-color: yellow;
        }

        * {
            font-family: Arial, sans-serif;
        }
    </style>
</head>
<body>
    <h1 id="title">CSS Selectors</h1>
    <p class="note">This is a paragraph.</p>
    <p>This is another paragraph.</p>
</body>
</html>

Summary

  • Element Selector → Selects elements by tag name.
  • ID Selector (#) → Selects one unique element.
  • Class Selector (.) → Selects one or more elements with the same class.
  • Universal Selector (*) → Selects all elements.
  • Group Selector (,) → Styles multiple elements with the same CSS rule.

CSS selectors are the foundation of styling because they determine which HTML elements receive specific styles.

No comments