samedi 2 janvier 2016

Can a label be placed separately from the form element it controls?

CSS Tricks documents something called, 'the checkbox hack,' in which elements are styled according to whether a checkbox is checked or not. This functionality is played with by styling the <label> element in order to make it appear as a link or a button, toggling the style of document elements when it is clicked.

In the demo provided, the checkbox is placed immediately following the label which describes it, and this is the configuration I normally see labels in—either immediately preceding, immediately following, or encapsulating the form element it controls.

However, in my specific use case scenario, I need the state of the checkbox to style multiple elements across multiple DOM nodes. As CSS has no parent selector, and the state of the checkbox is germane to the style of all the elements it controls, I believe it necessary to use relative CSS selectors such as ~ or + to style the elements. This necessitates placing the checkbox outside of the DOM node containing its label:

/* Checkbox Hack */

input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
label {
  cursor: pointer;
}
/* Default State */

div {
  background: green;
  width: 400px;
  height: 100px;
  line-height: 100px;
  color: white;
  text-align: center;
}
/* Toggled State */

input[type=checkbox]:checked ~ div label {
  color: red;
}
input[type=checkbox]:checked ~ div div {
  background-color: red;
}
<input type="checkbox" id="toggle-1">
<div>
  <label for="toggle-1">Toggle!</label>
</div>
<div>
  <div>A second element</div>
</div>

While this works (in Chrome, IE, Waterfox, and Vivaldi, at least), my question is about validity. Is it acceptable to place a <label> for a form element far away from that element itself, even outside the same DOM node? Are there any usability issues that might arise as a result of doing so?




Aucun commentaire:

Enregistrer un commentaire