Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS CSS class and descendant selectors practices

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #37688

    I would like to form a better understanding of when it is appropriate to use classes to target content as opposed to other available options, specifically, descendant selectors.

    In many cases, instead of using classes, it is possible to use descendant selectors to target the same elements. If the same thing can be accomplished in both ways, what is the logic between deciding an option ?

    Here are some example scenarios:

    1.
    a.



    /* target */





    .main > div > div

    b.









    .content

    2.
    a.


    /* target */


    /* target */




    .main > div:first-child
    .main > div:last-child

    b.










    .content1
    .content2

    3.
    a.









    .main > div div

    b.









    .content div

    What is the logic between deciding to use classes or descendant selectors ?

    #101429

    Ideally you want to keep your CSS as independent from your markup as possible. Tying styles into the structure isn’t a great idea, what if the structure changes? Then you would have to rewrite your styles when simply using classes would mean that your styles remain unaffected.

    The exception to this is if you have markup that will not change. Let’s take a navigation menu for example:

    The above markup isn’t going to change, so I don’t need to give the child elements classes, using the following would be fine:

    nav.main {
    ...
    }
    nav.main ul {
    ...
    }
    nav.main li {
    ...
    }
    nav.main a {
    ...
    }
Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘CSS’ is closed to new topics and replies.