CSS Selectors — How to Target Elements Correctly

Learn Web Development SEO & Digital Skills – Odurinde eLearning Forums Web Development CSS Selectors — How to Target Elements Correctly

  • This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #57540
    Emmanuel N
    Keymaster

    CSS selectors let you choose which HTML elements to style. When you understand selectors well, your layouts become easier to control and maintain.

    1. Element selector

    Targets all elements of a type.

    p {
      color: blue;
    }
    

    Styles every <p> on the page.

    2. Class selector

    Targets elements with a specific class. Most commonly used.

    .card {
      padding: 20px;
    }
    

    Used in HTML like:

    <div class="card"></div>
    

    3. ID selector

    Targets one unique element.

    #header {
      background: black;
    }
    

    Used in HTML:

    <div id="header"></div>
    

    Use IDs sparingly.

    4. Descendant selector

    Targets elements inside another element.

    .nav a {
      color: red;
    }
    

    Styles all links inside .nav.

    5. Child selector

    Targets direct children only.

    .menu > li {
      list-style: none;
    }
    

    Does not affect deeper nested items.

    6. Attribute selector

    Targets elements based on attributes.

    input[type="email"] {
      border: 1px solid blue;
    }
    

    Very useful for forms.

    7. Pseudo-classes

    Target elements based on state.

    Common ones:

    • :hover
    • :focus
    • :first-child
    • :last-child
    • :nth-child()

    Example:

    button:hover {
      background: green;
    }
    

    8. Specificity matters

    Priority order:

    1. Inline styles
    2. ID selectors
    3. Class / attribute / pseudo-class
    4. Element selectors

    Understanding specificity helps you avoid style conflicts.

    Mastering selectors gives you precise control over your CSS.

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.