Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Published
3 min read
CSS Selectors 101: Targeting Elements with Precision

1.Why CSS selectors are needed

CSS selectors are very important in CSS because they help target HTML elements that you want to style. Without selectors, you won't be able to style all elements the same way or it might apply to the wrong places.

2. Element selector

The element selector is the most basic selector in CSS, which directly targets elements by their HTML tag name (like p, div, h1).

How to Use

Just write the HTML element name, like p or h1, and then add styles inside curly braces. This will select all elements with that tag on the page.

3. Class selector

The class selector is a powerful tool in CSS that targets HTML elements based on their "class," so you can give specific groups different styles.

How to Use

Add a name in the element's class attribute in HTML (like class="content"), and in CSS, write the class name with a dot (.). This will apply styles to all elements with that class, no matter what tag they are.

4. ID selector

The ID selector is CSS's unique targeting tool, which selects only one specific element using its id attribute.

How to Use

Give the HTML element a unique id (like id="header"), and in CSS, write the id name with a hash (#). This will apply style only to that one element – there shouldn't be duplicate ids on the page.

5. Group selectors

Group selectors in CSS are a way to group multiple selectors together with a comma (,), so you can apply the same styles from one place.

How to Use

Separate different selectors (like element, class, or ID) with commas, and write common styles in curly braces. This will apply the same styles to all grouped selectors.

6. Descendant selectors

The descendant selector in CSS targets nested child elements inside a parent using a space ( ), no matter how many levels deep they are.

How to Use

Write the parent selector, then add a space and the child selector – this will apply styles to all matching descendants inside the parent.

7. Basic selector priority (very high level)

CSS selector priority (specificity) decides which style wins when multiple rules apply to the same element.

At a very high level, the priority order (Highest to Lowest) goes like this:

1.!important → If you add !important before any property, it won't be overridden by anything.

2.Inline Style (style="...") → Styles written directly inside the HTML tag have the highest priority (except !important).

3. ID Selector (#id) → div#header or #header are very specific.

4.Class/Pseudo-class/Attribute Selector (.class, :hover, [type]) → Classes have less priority than IDs but more than tag selectors.

5.Element/Tag Selector (div, p, h1) → These are the most basic with the lowest priority.