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.
Asked
Active
Viewed 122 times
0
-
1Do you want it semantically or do you want it actually working? You cannot have both. – PeeHaa Nov 17 '15 at 19:19
-
wat action you need to perform based on that clicks – Santosh Nov 17 '15 at 19:19
-
the images/checkboxes are part of a form and the destination should know the checked-ness of each of them... i.e. standard checkbox behaviour in a form – burnpanck Nov 17 '15 at 19:28
1 Answers
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
-
-
@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