选中复选框ID但在所有复选框下显示div

ale*_*oli 5 html css checkbox class

我有一个包含20个复选框的表单.

我想在选中复选框时显示div的内容.我得到了这样的结果

#toggle-content1 {
  display: none;
}

#mycheckbox1:checked~#toggle-content1 {
  display: block;
  height: 100px;
}

#toggle-content2 {
  display: none;
}

#mycheckbox2:checked~#toggle-content2 {
  display: block;
  height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<input type="checkbox" name="mycheckbox" id="mycheckbox1" value="0" />
<div id="toggle-content1">
  This content should appear when the checkbox is checked
</div>
<input type="checkbox" name="mycheckbox" id="mycheckbox2" value="0" />
<div id="toggle-content2">
  This content should appear when the checkbox is checked
</div>
Run Code Online (Sandbox Code Playgroud)

但是如果你尝试一下代码片段,你会注意到第一个复选框移动第二个(当打开div时),是否有办法将复选框留在一行并显示其他行的div?

css世界对我来说是新的,有一种方法可以编写20个复选框的代码而无需为每个div写css?

Tem*_*fif 4

你可以尝试这样的事情:

.content {
  display: none;
  width: 100%;
}

/*Use + to target only one .content*/
input[type=checkbox]:checked + .content {
  display: block;
  height: 50px;
}

.container {
  display: flex;
  flex-wrap: wrap;
}

input[type=checkbox] {
  order: -1; /*make all the input on the top*/
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <input type="checkbox" name="mycheckbox" value="0">
  <div class="content">
    0)This content should appear when the checkbox is checked
  </div>
  <input type="checkbox" name="mycheckbox" value="1">
  <div class="content">
    1)This content should appear when the checkbox is checked
  </div>
  <input type="checkbox" name="mycheckbox" value="2">
  <div class="content">
    2)This content should appear when the checkbox is checked
  </div>
  <input type="checkbox" name="mycheckbox" value="3">
  <div class="content">
    3)This content should appear when the checkbox is checked
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)