htmlcsscheckboxpseudo-classchecked

Deactive the :ckecked pseudoclass on an input[type="checkbox"] clicking on another element, in pure CSS


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>


Solution

  • 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>