0

What is the semantically correct HTML (HTML 5) markup for images that can be selected or deselected and should behave as checkbox in a form. Semantically, the images are not just styling of the checkboxes, but rather the actual objects that are selected.

burnpanck
  • 1,955
  • 1
  • 12
  • 36

1 Answers1

2

I would place both the image and the checkbox in a label element:

<label>
  <input type="checkbox" />
  <img src="//cdn.sstatic.net/stackoverflow/img/favicon.ico" />
</label>

This way you associate the image with the checkbox, and activating the image will toggle the state of the checkbox.

You can also hide the checkbox and use :selected + img to style the image depending on the checkedness.

label {
  float: left;
  clear: left;
}
label > input {
  opacity: 0;
}
label > img {
  opacity: .4;
  cursor: pointer;
}
label > :checked + img {
  opacity: 1;
}
<label>
  <input type="checkbox" />
  <img src="//cdn.sstatic.net/stackoverflow/img/favicon.ico" />
</label>
<label>
  <input type="checkbox" />
  <img src="//cdn.sstatic.net/stackoverflow/img/favicon.ico" />
</label>
<label>
  <input type="checkbox" />
  <img src="//cdn.sstatic.net/stackoverflow/img/favicon.ico" />
</label>
<label>
  <input type="checkbox" />
  <img src="//cdn.sstatic.net/stackoverflow/img/favicon.ico" />
</label>
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Indeed, I would like to hide the checkbox, and manipulate the image to show the selection state. I do not mind doing this in JS, but JS-free would certainly be nicer... – burnpanck Nov 17 '15 at 19:29
  • Ah, you gave the answer before I finished my comment... Thanks! – burnpanck Nov 17 '15 at 19:30
  • @burnpanck If you want to hide the checkbox, be aware `display: none` isn't accessible (it can't be toggled with the keyboard). You can use `opacity: 0` to hide it, `position: fixed` to make it out-of-flow, and negative `left` and `top` to place it outside the viewport. – Oriol Nov 17 '15 at 19:33