I have a label with 'for='the pointer to the checkbox input'' and as long as I know, this for can be added only for label. Therefore, I need to add inside of the label a
Solution 1:
It turns out you can make a <button>
operate an input, but only if you put the <label>
inside the <button>
.
<button type ="button" > <label for ="my-checkbox" > Button go outside the label</label > </button > <input type ="checkbox" id ="my-checkbox" >
Copy Although this contravenes the W3C specs:
The interactive element label must not appear as a descendant of the button element.
https://www.w3.org/TR/html-markup/label.html
Solution 2:
You can use transparent pseudo element that overlays the checkbox and the button itself that will catch mouse events.
Here's an example:
html:
<label > <input type ="checkbox" > <button class ="disable" > button</button > </label >
Copy css:
.disable {pointer-events :fill}
label {position :relative}
label :after {
position : absolute;
content : "" ;
width : 100% ;
height : 100% ;
background : transparent;
top :0 ;
left :0 ;
right :0 ;
bottom :0 ;
}
Copy Solution 3:
You can do dis:
<label >
<button ></button >
</label >
Copy CSS
label {
cursor : pointer; display : block;
}
button {
pointer-events : none;
}
Copy The display: block
on label will only be necessary so that the bounding box of the label fully encapsulates it's children (the button in this case).
Solution 4:
HTML:
<label for ="whatev" onclick ="onClickHandler" > <button > Imma button, I prevent things</button > </label >
Copy JS:
const onClickHandler = (e ) => {
if (e.target !==e.currentTarget ) e.currentTarget .click ()
}
Copy Target is the click target, currentTarget is the label in this case.
Without the if statement the event is fired twice if clicked outside of the event preventing area.
Not cross browser tested.
Solution 5:
The best solution is to style is like a button.
If you're using a CSS framework, like bootstrap, you can give the label classes such as btn and btn-default. This will style it like a button. You may need to adjust the css property of the line-height manually like so:
label .btn {
line-height : 1.75em ;
}
Copy Then, to get the on click styles as a button, add these styles:
input [type=radio] :checked ~ label .btn {
background-color : #e6e6e6 ;
border-color : #adadad ;
color : #333 ;
}
Copy This will take the input that is checked and give the next label element in the dom that has the class btn, bootstrap btn-default button clicked styles. Adjust colors as fit.
Post a Comment for "Button Inside A Label"