CSS Selector

CSS selectors are the heart of styling HTML elements. They specify which elements a particular set of CSS rules should be applied to.

Types of Selectors

1. Simple Selectors

  • Element selectors: Target elements based on their tag name.
p {
    color: blue;
}

This will apply blue color to all paragraph elements.

  • ID selectors: Target a specific element based on its unique ID attribute.
<h1 id="main-heading">This is the main heading</h1>
#main-heading {
    font-size: 36px;
    color: red;
}

This will style the heading with the ID “main-heading”.

  • Class selectors: Target elements with a specific class attribute.
<p class="highlight">This is a highlighted paragraph.</p>
.highlight {
    background-color: yellow;
}

This will apply a yellow background to all elements with the class “highlight”.

2. Combinators

  • Descendant combinator (space): Selects elements that are descendants of another element.
div p {
    font-weight: bold;
}

This will bold all paragraph elements inside a div element.

  • Child combinator (>): Selects elements that are direct children of another element.
ul > li {
    list-style-type: square;
    margin-left: 20px;
}

This will style only the direct list items within an unordered list.

  • Adjacent sibling combinator (+): Selects an element that is immediately preceded by another element.
h2 + p {
    font-style: italic;
}

This will italicize the paragraph that comes directly after an h2 element.

  • General sibling combinator (~): Selects elements that are preceded by another element.
h2 ~ p {
    text-align: right;
}

This will right-align all paragraphs that follow an h2 element.

3. Pseudo-classes

  • Structural pseudo-classes: Select elements based on their position in the document structure.
p:first-child {
    font-weight: bold;
}

This will bold the first paragraph within its parent.

  • State pseudo-classes: Select elements based on their state.
a:hover {
    color: blue;
}

This will change the link color to blue when the mouse hovers over it.

Additional Tips

  • Use specific selectors to avoid unintended styling.
  • Combine selectors for precise targeting.
  • Consider using CSS preprocessors for advanced selector features.

By mastering CSS selectors, you can create highly targeted and efficient styles for your web pages.

Share this Tutorials

CSS Selector

Or copy link

CONTENTS
Scroll to Top