Home > Enterprise >  Deactive the :ckecked pseudoclass on an input[type="checkbox"] clicking on another element
Deactive the :ckecked pseudoclass on an input[type="checkbox"] clicking on another element

Time:07-29

I realized the Css click with che :checked pseudoclass. When I click on the label associated with the input (checkbox) I give a margin to the label.

I would know if there is a way to deactive the pseudoclass :checked on the input clicking on ANOTHER element (I already know that clicking on the same checkbox unflag (better uncheck) the input). I would know if there is some hack.

input {
        display: none;
      }

      input:checked   label {
        margin-left: 5em;
      }

      input   label::before {
        content: "Give margin";
        cursor: pointer;
      }

      input:checked   label::before {
        content: "No Margin";
      }
<body>
    <input type="checkbox" name="check" id="check" />
    <label for="check"></label>
  </body>

CodePudding user response:

Use radio inputs. Click the red square to disable the margin

input {
  display: none;
}

#check:checked label {
  margin-left: 5em;
}

#check label::before {
  content: "Give margin";
  cursor: pointer;
}

#check:checked label::before {
  content: "No Margin";
}

[for=disable] {
  position:absolute;
  right:0;
  bottom:0;
  width:150px;
  aspect-ratio:1;
  background:red;
  cursor:pointer;
}
<body>
  <input type="radio" name="check" id="check" />
  <label for="check"></label>
  
  
  <input type="radio" name="check" id="disable" />
  <label for="disable"></label>
</body>

CodePudding user response:

I'm using two labels.

It's ok to have more labels tied to the same input label for the html specification. However there is some problem for the accessibility. Below there is a solution that should to fit accessibility too.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      input {
        display: none;
      }

      input:checked   label {
        margin-left: 5em;
      }

      input   label::before {
        content: "Give margin";
        cursor: pointer;
      }

      input:checked   label::before {
        content: "No Margin";
      }
    </style>
  </head>
  <body>
    <input type="checkbox" aria-labelledby="l1 l2" name="check" id="check" />
    <label id="l1" for="check"></label>

    <label id="l2" for="check">Another element</label>
  </body>
</html>

  • Related