首页 > 解决方案 > 比视口更宽的 div

问题描述

我目前正在使用复选框 hack 编写响应式菜单,并注意到当我的菜单在单击汉堡图标后出现时,它比视口宽。菜单具有固定位置和弹性显示。我在元素周围添加了红色边框以显示此问题。以下是相关代码:

/* General styles */
html, body { height: 100%; }
body {
  font-family: 'Miriam Libre', sans-serif;
}
a {
  color: white;
  text-decoration: none;
  transition: 0.2s;
}
a:hover {
  color: #ea3c53;
}
/* Navigation styles */
nav {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background: #222222;
}
.donate {
  position: absolute;
  margin: 21px;
}
nav .brand {
  display: block;
  height: 70px;
  margin: 10px auto;
}
input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
nav label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 21px;
  background: #63E2C6;
  cursor: pointer;
  z-index: 2;
}
nav > label > span {
  display: block;
  margin: 4px auto;
  height: 4px;
  width: 25px;
  border-radius: 1px;
  background: #ffffff;
  transition: 0.5s;
}
.menu {
  display: flex;
  position: fixed;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0;
  top: -100vh;
  left: 0;
  height: 100vh;
  width: 100%;
  background: #222;
  list-style-type: none;
  border: 1px solid red;
  transition: top 0.5s cubic-bezier(0.3, 0.1, 0.3, 0.85);
}
.menu li {
  font-size: 30px;
  border: 1px solid red;
}
input[type=checkbox]:checked ~ .menu {
  top: 0;
}
<nav>
    <!-- Top bar -->
    <a href="link" target="_blank" class="donate">Donate</a>
    <img src="media/logo2.png" alt="Logo" class="brand">
    <input type="checkbox" id="nav">
    <label for="nav">
      <span></span>
      <span></span>
      <span></span>
    </label>
    <ul class="menu">
      <li><a href="#home">Home.</a></li>
      <li><a href="#mission">Mission.</a></li>
      <li><a href="#contact">Contact.</a></li>
    </ul>
  </nav>

所以,我的问题是,为什么会这样?毕竟,我确实将宽度设置为 100%,而不是 110%。

标签: htmlcssflexbox

解决方案


您的 body 元素有边距。添加:

body {
  margin: 0;
}

您的元素上还有默认边距和填充ul,也被设置为width: 100%;

我建议检查你所有的主要容器,在你的浏览器检查器中查看它们,当你在一个你可能没有考虑到的元素上有额外的间距时,它们会突出显示。


推荐阅读