ga-wdi-boston / html-css

High-level overview of HTML and CSS.
Other
4 stars 170 forks source link

Best practices: ids #10

Closed jrhorn424 closed 8 years ago

jrhorn424 commented 8 years ago

IDs have a number of restrictions that other attributes don't have. In the first project, there is a temptation to use IDs to easily grab inputs instead of spending the cognitive load to write a good selector. This habit, if unchecked, leads to developer code like this:

<p class="centerHeader">Submit a project</p>
<label for="title">TITLE:</label>
<input type="text" name="title" class="projectForm" id ="project-title">
<label for="category">CATEGORY:</label>
<input type="text" name="category" class="projectForm" id ="project-category">
<label for="imageURL_sm">SMALL IMAGE URL:</label>
<input type="text" name="imageURL_sm" class="projectForm" id ="project-imageURL_sm">
<label for="imageURL_lg">LARGE IMAGE URL:</label>
<input type="text" name="imageURL_lg" class="projectForm" id ="project-imageURL_lg">
<label for="siteURL">SITE URL:</label>
<input type="text" name="siteURL" class="projectForm" id ="project-siteURL">
<label for="codeURL">CODE URL:</label>
<input type="text" name="codeURL" class="projectForm" id ="project-codeURL">
<label for="body">DESCRIPTION:</label>
<textarea rows="4" cols="50" name="description" class="projectForm" id="project-description"></textarea>
<button id="project-submit">Submit</button>
<p class="whitespace"></p>

CSS best practices suggest never selecting for styles on IDs. IDs should only be used sparingly in javascript. Our sass linter warns on this, so the earlier we explain that there are better selector strategies, the better.

jrhorn424 commented 8 years ago

Related #11 and #2

gaand commented 8 years ago

html5 allows for embedding inputs in labels. This eliminates the need for ids to relate the labels to their inputs, e.g.

<label>
  Label Text
  <input type="text" name="bob">
</label>
raq929 commented 8 years ago

I thought the 'for' in a label was what related it to it's input?

gaand commented 8 years ago

for="<id of input>" creates the relation, so the input then needs an id.

Ids on inputs aren't that useful. Names, which are form scope, are preferred for almost all use cases.

Wrapping the input in the label removes the need to connect via and id which must be unique for the document.

@raq929 If you'd like to discuss further, I'm happy to here or in person.

jrhorn424 commented 8 years ago

Ids on inputs aren't that useful. Names, which are form scope, are preferred for almost all use cases.

:heart: