Hello and welcome to our community! Is this your first visit?
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
    Thanked 0 Times in 0 Posts

    Which CSS selector?

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

    <!DOCTYPE html>
    <html lang="en">
        <meta charset="UTF-8">
        <title>Which CSS selector</title>
            [for="married"] {
                outline: 1px solid red;
            <label for="name">Name</label>
            <input type="text" id="name">
            <label for="married">Married</label>
            <input type="checkbox" id="married">
    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. #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Sydney, Australia
    Thanked 932 Times in 919 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.
    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