homepage Welcome to WebmasterWorld Guest from 54.204.127.191
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, Moderator: open

CSS Forum

    
Which CSS selector?
Rain_Lover




msg:4658371
 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">

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

  •  

    graeme_p




    msg:4658385
     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.

    Readie




    msg:4659203
     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