html - 纯CSS复选框切换菜单

标签 html css checkbox nav

我正在尝试创建一个菜单,当复选框被选中/取消选中时,该菜单将进行切换。
我已经创建了以下html结构:

<header>
  <div>
    <label for="navmenu"><span class="icon-menu"></span></label>
    <input type="checkbox" id="navmenu">
    <nav>
      <ul>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </nav>
  </div>
</header>

<span>元素通过css包含图标字体中的图标。
这是我写的css:
header {
  position: fixed;
  width: 100%;
  text-align: center;
  font-size: 1.25em;
  letter-spacing: 1px;
  line-height: 2em;
  background: #299a97;
  color: white; }
header h1 {
  font-size: 1em;
  font-weight: normal; }
header div {
  width: 2em;
  position: fixed;
  top: 0;
  left: 0; }
header div input[type=checkbox] {
  position: absolute;
  top: 1em;
  left: 1em;
  opacity: 0; }

nav {
  width: 100%;
  position: fixed;
  top: 2.5em;
  display: none; }
nav li {
  height: 2em;
  line-height: 2em;
  padding: 0 1em;
  background: #2eaeab;
  border-bottom: 1px solid #299a97;
  color: white; }
nav li a {
  display: block;
  width: 100%;
  text-decoration: none;
  color: white; }
nav span {
  margin-right: 1em; }

页眉div输入[类型=复选框]:选中~导航{
显示:block;}
现在,由于某些原因,当我选中复选框时,导航菜单不会出现。我做错了什么?

最佳答案

四处移动navinput[type=checkbox]:checked ~ nav。否则nav会用display: none覆盖之前的所有内容。
更新
只是为了详细说明。由于某些原因,当定位为绝对时,复选框不会取消选中。这无关紧要,因为您不需要查看复选框,这样我们就可以完全不显示它,让您的标签检查和取消选中我们隐藏的复选框。
有小提琴-Fiddle link!
用隐藏复选框更新
CSS

  input[type=checkbox] {
     display: none;
   }

 nav {
      position: fixed;
      display: none;
  }

  input[type=checkbox]:checked ~ nav {
      display: block;
  }

关于html - 纯CSS复选框切换菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23823514/

相关文章:

html - 如何在 html 和 css 中将图像调整为几何图形?

jquery - 为什么 jQuery 切换在鼠标移动/悬停时不断变化

javascript - 如何将复选框列表的选定项绑定(bind)到 Ruby on Rails 中下拉列表中的选定项?

javascript - 如何在页面加载后添加 ng-app?

html - 如何围绕文本换行范围缩小 flex 元素?

html - 当文本太长时,如何制作带有边距的流畅文本居中框?

javascript - 对 D3 中可折叠树形图中父节点上的 "Number of child' s 进行编号

javascript - jQuery .slideToggle() 不工作

C# Datagridview 复选框值

javascript - 如果选择了特定项目之一,则禁用所有复选框列表项目