Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Nov 2009
    Posts
    200
    Thanks
    23
    Thanked 0 Times in 0 Posts

    Which CSS selector?

    Sometimes I find it difficult to choose the right CSS selector. Consider this, for example:

    Code:
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>Which CSS selector</title>
        <style>
            [for="married"] {
                outline: 1px solid red;
            }
        </style>
    </head>
    
    <body>
        <form>
            <label for="name">Name</label>
            <input type="text" id="name">
            <label for="married">Married</label>
            <input type="checkbox" id="married">
        </form>
    </body>
    
    </html>
    I can get the same result with:

    • label:nth-child(3)
    • label:nth-of-type(2)
    • #name + label
    • etc.


    I can even give the element an ID and get it directly. But isn't it better to keep your HTML tidier/smaller?

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Use the one that is least likely to be changed if you rearrange the HTML. For example with the code you have there if you add another label and input between the name and married ones then of the selectors you specified only the one you actually included in the HTML would still point to the right place.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •