homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / CSS
Forum Library, Charter, Moderators: not2easy

CSS Forum

Which CSS selector?

Msg#: 4658369 posted 4:33 am on Mar 29, 2014 (gmt 0)

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

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



    WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month

    Msg#: 4658369 posted 6:18 am on Mar 29, 2014 (gmt 0)

    I would avoid nth child as it is harder to maintain - it breaks more easily if you make minor changes to your HTML - e.g. change the order of the inputs.

    I think [for=married] is fine as there is no reason it should change. unless you completely redo the form.


    WebmasterWorld Senior Member 5+ Year Member

    Msg#: 4658369 posted 3:24 pm on Apr 1, 2014 (gmt 0)

    According to sitepoint, #name + label would give you the best backwards compatibility with old browsers.

    If all available solutions achieve my goal without any compromises, then "how many people will this serve?" is my go-to decider.

    Global Options:
     top home search open messages active posts  

    Home / Forums Index / Code, Content, and Presentation / CSS
    rss feed

    All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
    Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
    WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
    © Webmaster World 1996-2014 all rights reserved