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)

5+ Year Member Top Contributors Of The Month

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?
  • graeme_p

    6:18 am on Mar 29, 2014 (gmt 0)

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

    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)

    WebmasterWorld Senior Member 5+ Year Member

    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.

    Featured Threads

    Hot Threads This Week

    Hot Threads This Month