Learn CSS Selectors

CSS selectors are a fundamental part of styling and formatting web pages. They allow you to target and apply styles to specific HTML elements. CSS selectors consist of different patterns that match one or more elements in an HTML document. Let's go through some common types of selectors:

  • Universal Selector (*): The asterisk symbol targets all elements on the page.
* {
  /* Styles applied to all elements */
}
  • Type Selector: Targets elements based on their HTML tag name.
p {
    /* Styles applied to all <p> elements */
}
  • Class Selector (.classname): Targets elements with a specific class attribute.
.highlight {
    /* Styles applied to elements with class="highlight" */
}
  • ID Selector (#idname): Targets a single element with a specific ID attribute.
#header {
   /* Styles applied to the element with id="header" */
}
  • Descendant Selector (whitespace): Targets elements that are descendants of another element.
ul li {
    /* Styles applied to <li> elements that are descendants of <ul> elements */
}
  • Child Selector (>): Targets elements that are direct children of another element.
nav > ul {
    /* Styles applied to <ul> elements that are direct children of <nav> */
}
  • Adjacent Sibling Selector (+): Targets an element that is immediately preceded by a specific element.
h2 + p {
    /* Styles applied to <p> elements that directly follow <h2> elements */
}
  • General Sibling Selector (~): Targets elements that are siblings of a specific element.
h2 ~ p {
    /* Styles applied to <p> elements that are siblings of <h2> elements */
}
  • Attribute Selector ([attribute]): Targets elements based on their attributes.
[type="submit"] {
    /* Styles applied to elements with type="submit" attribute */
}
  • Combining Selectors: You can combine multiple selectors to create more specific targeting.
nav ul.nav-list {
    /* Styles applied to <ul> elements with class="nav-list" that are descendants of <nav> elements */
}

These are just some of the basic CSS selectors. By using various combinations of these selectors, you can effectively target and style different elements in your HTML documents. Remember that good use of selectors can help maintain a clean and organized CSS structure.

Published on: 13-Aug-2023