Log in

View Full Version : Which CSS selector?



Rain Lover
03-29-2014, 04:47 AM
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?

jscheuer1
03-29-2014, 05:16 AM
Each method has its own merits depending upon the situation.

There are various goals to keep in mind (just off the top of my head, in no particular order, there are probably others):


Simple and concise code (both HTML and CSS)
Code (both HTML and CSS) that's easy to understand with the human eye/mind
Code (both HTML and CSS) that's reusable across as many pages of the site as possible
CSS code that establishes a visual theme that can also be easily tweaked in just a few places to create dramatic and/or subtle variations on that theme

Rain Lover
03-29-2014, 02:58 PM
Each method has its own merits depending upon the situation.

There are various goals to keep in mind (just off the top of my head, in no particular order, there are probably others):


Simple and concise code (both HTML and CSS)
Code (both HTML and CSS) that's easy to understand with the human eye/mind
Code (both HTML and CSS) that's reusable across as many pages of the site as possible
CSS code that establishes a visual theme that can also be easily tweaked in just a few places to create dramatic and/or subtle variations on that theme


Thanks for the answer!