Skip to main content

Command Palette

Search for a command to run...

CSS Selectors

Published
•3 min read
CSS Selectors

We know how to write HTML, but how to set some properties to that HTML element? 🤔
To set the properties to HTML elements, we have CSS selectors!!

What are CSS selectors?

CSS selectors define the elements to which a set of CSS rules apply.

Basic selectors

1. Universal selector

A universal selector selects all elements which are present in HTML dom.
Syntax: * { CSS body }

2. Type selector

A type selector will select a specific tag.
Syntax: tagname { CSS body }
For example: p will select all the <p> tags in HTML DOM.

3. Class selector

A class selector selects all the elements with the same class attribute.
Syntax: .classname { CSS body }
Example:

<div classname = "container"></div>
<div classname = "container"></div>
.container {
    width: 100%;
    margin: auto;
}

4. ID selector

An ID selector selects an elements based on its ID attribute.
Syntax: #id { CSS body }
Example:

<div id = "container"></div>
#container {
    width: 100%;
    margin: auto;
}

5. Attribute selector

An attribute selector selects all the elements with the same attribute.
Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
Example:

<label>
    <input type = "radio" />
    This is input
</label>
input[type = "radio"] {
    font-size: 1.5rem;
}

Grouping Selectors

, is used to group various elements for which we have to set the same properties.
Syntax: a, b { CSS body }
Example: div, section

Combinators

1. Descendant combinator

" " selects nodes that are descendants of the first element.
Syntax: a b { CSS body }
Example: div p will match all <p> elements that are inside a <div> element.

2. Child combinator

> combinator selects the elements that are direct children of the first element.
Syntax: a > b { CSS body }
Example: div > span will match all <span> which are direct children of <div> element.

3. General sibling combinator

~ combinator selects siblings. This means that the elements are consecutively and both share the same parent. Syntax: a ~ b Example: p ~ span will match all <span> elements that follow a <p>, immediately or not.

4. Adjacent sibling combinator

The + combinator only matches the second element if it immediately follows the first element. Syntax: a + b { CSS body }
Example: h1 + span will match all <span> elements that immediately follow an <h1> element.

5. Column combinator Experimental

|| combinator selects nodes which belong to a column.
Syntax: a || b { CSS body }
Example: col || td will match all <td> elements that belong to the <col> scope.

So that's it! These are all the CSS selectors covered.
We learned how to select an element with the help of CSS selectors. We learned the basic selectors, grouping selectors, and combinators. Now you can easily select any element and pace your CSS journey!🤩