Skip to main content

Command Palette

Search for a command to run...

CSS Selectors : Targeting Elements with Precision

Published
2 min read

CSS Selectors are patterns used in CSS to select and target HTML elements so that styles can be applied to them. They define which elements on a web page should receive specific styling rules.

  • Used to select HTML elements based on tag name, class, id, or attributes

  • Help apply styles like color, font, spacing, and layout

  • Make web pages structured, consistent, and visually appealing

There are mainly 5 types of selectors.

  1. Basic Selectors

Basic selectors in CSS are simple tools used for selecting by HTML element name (e.g., h1), class (.class Name), ID (#idName), or universally (* for all elements).

a). Universal Selector (*): Selects all elements on the page and applies the same style universally.

Example: Setting the font color for every element.

* {
    color: red;
}

b). Element Selector: Targets all elements of a specific type, such as paragraphs or headers.

Example: Setting a common font size for all paragraphs

p {
  font-size: 16px;
}

c). Class Selector (.): Applies styles to elements with a specific class attribute.

Example: Making all buttons have a blue background.

<html>
<head>
    <style>
        .button {
            background-color: blue;
            color: white;
        }
    </style>
</head>
<body>
    <button class="button">Click Me!</button>
</body>
</html>

d). ID Selector (#): Styles a single element identified by its unique id.

Example: changing the background color of a header.

<html>
<head>
    <style>
        #header {
            background-color: gray;
        }
    </style>
</head>
<body>
    <div id="header">This is the header section.</div>
</body>
</html>
  1. Combinator Selectors

Used to define relationships between selectors, allowing you to style elements based on their hierarchy or positioning in the document. Common combinators include descendant ( ), child (>), adjacent sibling (+), and general sibling (~).

a). Descendant Selectors: Targets an element inside another, such as paragraphs inside div .

Example: Styling paragraphs inside a div.

<html>
<head>
    <style>
        div p {
            color: red;
        }
    </style>
</head>
<body>
    <div>
        <p>This paragraph inside a div will be red.</p>
    </div>
</body>
</html>

b). Child Selector (>): They only affects the direct child elements of a parent.

Example: Styling direct children paragraphs of a div.

<html>
<head>
    <style>
        div>p {
            margin-left: 20px;
        }
    </style>
</head>
<body>
    <div>
        <p>This is a direct child and has a left margin.</p>
        <div>
            <p>This is not a direct child.</p>
        </div>
    </div>
</body>
</html>