如何使用html+css和输入复选框来制作响应式菜单?

3
当复选框被点击时,navmargin:left 应该增加并进入屏幕。再次点击时,它应该减少并离开屏幕。但我的代码没有按照这个方式工作。我的代码有什么问题? Html
<input type="checkbox" id="res-nav">
<label for="res-nav"><i class="fa fa-reorder" style="font-size:36px"></i></label>

样式

 body label {
    position: fixed;
    display: block;
    margin-left:-100px; 
    margin-top: -115px; 
    z-index:99;
}

nav{
    margin-left:-130px;
    transition: all 0.5s;
    -moz-transition: all 0.5s;
    -ms-transition: all 0.5s;
    -o-transition: all 0.5s;
    -webkit-transition: all 0.5s;
}

#res-nav:checked ~ nav {
    margin-left:50px;
}

你理解它应该如何工作了吗?你的<nav>元素确切的位置在哪里? - connexo
你的类选择器不正确。@Ahmet - pixlboy
body 标签中的 nav。你问了吗? - Ahmet Yılmaz
3个回答

2

label {
    position: fixed;
    display: block;
    margin-left:-100px; 
    margin-top: -115px; 
    z-index:99;
}

nav{
    margin-left:-9999px;
    transition: all 0.5s;
    -moz-transition: all 0.5s;
    -ms-transition: all 0.5s;
    -o-transition: all 0.5s;
    -webkit-transition: all 0.5s;
    background:tomato;
    max-width:100vw;
}

#res-nav:checked ~ nav {
    margin-left:0;
}
<input type="checkbox" id="res-nav">
<label for="res-nav"><i class="fa fa-reorder" style="font-size:36px"></i>s</label>
<nav>Navbar</nav>


我的代码和你的完全一样。但我不明白为什么它不起作用。 - Ahmet Yılmaz
有一些更改已经进行了。但是您的示例在输入后没有<nav>元素。 - Martin Lecke
好的,我明白了。在 CSS 中写 ~ 符号时,跟随符号的元素必须在第一个元素之后。先是 <checkbox>,然后是 <nav>。 - Martin Lecke

1
这是您要找的吗?

.nav{
    margin-left:-120px;
    transition: all 0.5s;
}

#res-nav:checked ~ .nav {
    margin-left: 10px;
}
<input type="checkbox" id="res-nav">
<label for="res-nav" class="nav">
 <i class="fa fa-reorder" style="font-size:36px">Hello</i>
</label>


0

这种方式是否适合您的需求?如您所见,我使用了位置而非边距,如果您想在导航标签上滚动,可以在嵌套的 div 中使用溢出吗?

我将最小高度设置为该高度,因为 vh 在旧浏览器中不起作用,因此这是一个简单的备份解决方案。您也可以使用一些 JS 来计算您想要的像素精确高度,但是完全不使用 JS,我认为这已经是一个足够好的解决方案了。

body {
  background: white;
}

body label {
    position: fixed;
    display: block;
    margin-left:-100px; 
    margin-top: -115px; 
    z-index:99;
}

#res-nav {
  position: fixed;
  height: 20px;
  width: 40px;
  top: 0;
  left: calc(50% - 20px);
}

nav{
    position: fixed;
    left: -9999px;
    z-index: 999999;
    top: 20px;
    background: rgba(0, 0, 0, 0.75);
    transition: all 0.5s;
    -moz-transition: all 0.5s;
    -ms-transition: all 0.5s;
    -o-transition: all 0.5s;
    -webkit-transition: all 0.5s;
    width: 100%;
    height: 100vh;
    min-height: 9999px;
    max-height: 100vh;
}

nav * {
  color: white;
}

#res-nav:checked ~ nav {
  left: 0;
}
<div>
  <input type="checkbox" id="res-nav">
  <label for="res-nav"><i class="fa fa-reorder" style="font-size:36px"></i></label>
  <nav>
    <ul>
      <li><a href="#">hello world</a></li>
    </ul>
  </nav>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接