0

So I have a div that appears/disappears on clicking checkbox.


    <input type="checkbox" id="btn">
    <div id="box"></div>

    #box {
        display: none;
        width: 100px;
        height: 100px;
    }

    #btn:checked + #box
        display: block;
    }

But I also want to add an option to close it by clicking anywhere outside this box. How can I do it?

  • 1
    Does this answer your question? [How do I detect a click outside an element?](https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – evolutionxbox Jun 27 '22 at 10:50

1 Answers1

0

Check the below code. You can use label for to achieve this behavior. You click a box outside of checkbox and it gets checked as you wanted.

label {
  display: block;
  margin-top: 100px;
  width: 200px;
  height: 200px;
  background: limegreen;
}

#btn:checked~#box {
  display: block;
}

#box {
  margin-top: 50px;
  display: none;
  width: 200px;
  height: 200px;
  background: red;
}
<input type="checkbox" id="btn">
<label for="btn"></label>

<div id="box">
</div>
Erenn
  • 625
  • 6
  • 18