DEV Community

Lokesh
Lokesh

Posted on

CSS Selectors

1. Element Selector

An element selector selects all HTML elements with a particular tag name.

p {
    color: blue;
}
Enter fullscreen mode Exit fullscreen mode

Here, all <p> elements will have blue text.

2. ID Selector

An ID selector is used to select an element with a specific ID. In CSS, we use the # symbol before the ID name.

HTML:

<h1 id="title">Welcome</h1>
Enter fullscreen mode Exit fullscreen mode

CSS:

#title {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

Here, the heading with the ID title will have red text.

An ID should be unique within a webpage.

3. Class Selector

A class selector is used to select elements with a particular class name. In CSS, we use the . symbol before the class name.

HTML:

<p class="message">Hello World!</p>
<p class="message">Welcome to CSS!</p>
Enter fullscreen mode Exit fullscreen mode

CSS:

.message {
    color: green;
}
Enter fullscreen mode Exit fullscreen mode

Both paragraphs will have green text.

We can use the same class on multiple HTML elements.

4. Universal Selector

The universal selector selects all elements on a webpage. It uses the * symbol.

* {
    margin: 0;
    padding: 0;
}
Enter fullscreen mode Exit fullscreen mode

This removes the default margin and padding from all elements.

5. Group Selector

A group selector allows us to apply the same styles to multiple selectors.

h1, h2, p {
    color: purple;
}
Enter fullscreen mode Exit fullscreen mode

Here, all <h1>, <h2>, and <p> elements will have purple text.

This helps us avoid writing the same CSS rules separately.

6. Descendant Selector

A descendant selector selects elements that are inside another element, at any level.

HTML:

<div>
    <p>This paragraph is inside the div.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

div p {
    color: orange;
}
Enter fullscreen mode Exit fullscreen mode

Here, paragraphs inside the <div> will have orange text.

7. Pseudo-class Selector

Pseudo-classes are used to style elements in a particular state.

For example, :hover applies styles when the mouse pointer moves over an element.

button:hover {
    background-color: blue;
    color: white;
}
Enter fullscreen mode Exit fullscreen mode

Here, the button's background becomes blue when the pointer hovers over it.

Top comments (0)