Welcome to WebmasterWorld Guest from

Forum Moderators: not2easy

Message Too Old, No Replies

Which CSS selector?

4:33 am on Mar 29, 2014 (gmt 0)

Junior Member

5+ Year Member Top Contributors Of The Month

joined:Mar 1, 2010
posts: 194
votes: 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?
  • 6:18 am on Mar 29, 2014 (gmt 0)

    Senior Member from LK 

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

    joined:Nov 16, 2005
    votes: 56

    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.
    3:24 pm on Apr 1, 2014 (gmt 0)

    Senior Member

    WebmasterWorld Senior Member 5+ Year Member

    joined:Dec 13, 2009
    votes: 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.