Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

html - How does css checkbox hack work?

I just came across the switch toggle button which is created only using css. It known as the checkbox hack.

For those who doesn't know what a checkbox css hack is, Please read it here

https://css-tricks.com/the-checkbox-hack/

I tried it out and it was working perfectly fine. But I didn't understand how this is working because we are not clicking on the checkbox.

So I have 2 questions

  1. How is this working ?

  2. Instead of absolute positioning I tried it with display: none; It still worked. Does this method have any drawbacks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The way it works is by using the <label> element. Any input element can (and usually should) have a label. You can tell the browser which label belongs to which label by using a for attribute, referring to the input's name:

<input name="myName" />
<label for="myName">Label</label>

Whenever you click the label, it focuses the input (or in case of checkboxes, toggles it).

The label and checkbox don't have to be near each other. You could add a few hidden checkboxes at the start or end of a document and place the labels anywhere on the page, and they'd still focus the input.

Hiding the checkbox through display: none could cause buggy behavior on certain browsers. Just hiding it from view by a position: absolute is safer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...