"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Style Specific Nested Elements across Different Parent Structures?

How to Style Specific Nested Elements across Different Parent Structures?

Published on 2024-11-04
Browse:431

How to Style Specific Nested Elements across Different Parent Structures?

Styling Nested nth-child Elements across Multiple Parents

Seeking a solution to style specific nested elements within varying parent structures, consider the following markup:

  • one
  • two
  • three
  • four


The goal is to apply styles to "one" and "three," regardless of whether they are the first children of each

    .

    Limitation of :nth-child()

    Attempts to use :nth-child() fall short because it only applies to elements that share the same parent. In this scenario, the CSS selector .foo li:nth-child(1), .foo li:nth-child(3) would only target the first children of each

      .

      Alternative Solutions

      JavaScript:

      Using a library like jQuery allows you to select elements using JavaScript's powerful filtering capabilities. For instance, the following script would target the first and third

    • elements within the .foo container:
      $('.foo li:eq(0), .foo li:eq(2)')

      Explicit Element Marking:

      You can explicitly mark the desired elements with classes or IDs to enable their selection via CSS. For example, adding classes to the first and third

    • elements:

    • one
    • two

  • three

    • four

    • Then, you can use CSS to target the marked elements:

      .foo .first,
      .foo .third {
          color: red;
      }
      Release Statement This article is reprinted at: 1729685066 If there is any infringement, please contact [email protected] to delete it
      Latest tutorial More>

      Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

      Copyright© 2022 湘ICP备2022001581号-3