【问题标题】:Horizontal blank space though margin property is not set [duplicate]未设置边距属性的水平空格[重复]
【发布时间】:2020-04-27 06:55:35
【问题描述】:

我在学习 CSS 时遇到了这个问题。我试图搜索这个,但找不到任何正确的答案。有些导致我margin collapsing,但它不会发生在水平边距上。

#nav-bar {
  position: fixed;
  top: 0px;
  left: 0px;
  height: 60px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #be3144;
}

#nav-list {
  display: flex;
  margin-right: 4rem;
}

.nav-link {
  text-decoration: none;
  color: white;
  padding: 0 1.6rem 0 1.6rem;
  height: 60px;
  weight: 100%;
  display: flex;
  align-items: center;
  font-size: 1.3rem;
}

#welcome-section {
  background-color: #3a3d40;
  height: 100vh;
  display: flex;
  flex-direction: column;
  text-align: center;
  align-items: center;
  justify-content: center;
  margin-top: 60px;
}
<nav id="nav-bar">
  <div id="nav-list">
    <a href="#welcome-section" class="nav-link">About</a>
    <a href="#tile" class="nav-link">Work</a>
    <a href="#contact" class="nav-link">Contact</a>
  </div>
</nav>

<section id="welcome-section">
  <h1>Hey I am Mimic</h1>
  <h4>a web developer</h4>
</section>

导航栏下方的#welcome-section 左右两边都有空格,虽然我没有设置任何边距属性。 此外,任何关于样式化 HTML/CSS 的建议和建议都值得赞赏。提前致谢。

【问题讨论】:

  • 一些 HTML 元素有默认样式; body 就是其中之一(其他包括 ph1h2 等)——你需要覆盖身体的边距才能完成你想要的。请注意,对于nav,您通过制作硬定位元素(即top: 0)来隐式执行此操作
  • 正文有一个margin: 8px。您可以删除它或将margin: 0 -8px; 添加到welcome-section
  • 快速注释,在任何属性上设置数值时,您需要使用度量单位(即pxem 等)但如果您将值设置为零,测量单位不是必需的(因为它变得无关紧要)所以你可以简单地说margin: 0; - 这会在你的CSS上在这里和那里节省几个字节;)

标签: html css


【解决方案1】:

这是因为页面的&lt;body&gt;默认有边距。

通过添加以下内容摆脱它,它应该可以工作......

body {
  margin:0;
}

body {
  margin:0;
}

#nav-bar {
  position: fixed;
  top: 0px;
  left: 0px;
  height: 60px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background-color: #be3144;
}

#nav-list {
  display: flex;
  margin-right: 4rem;
}

.nav-link {
  text-decoration: none;
  color: white;
  padding: 0 1.6rem 0 1.6rem;
  height: 60px;
  weight: 100%;
  display: flex;
  align-items: center;
  font-size: 1.3rem;
}

#welcome-section {
  background-color: #3a3d40;
  height: 100vh;
  display: flex;
  flex-direction: column;
  text-align: center;
  align-items: center;
  justify-content: center;
  margin-top: 60px;
}
<nav id="nav-bar">
  <div id="nav-list">
    <a href="#welcome-section" class="nav-link">About</a>
    <a href="#tile" class="nav-link">Work</a>
    <a href="#contact" class="nav-link">Contact</a>
  </div>
</nav>

<section id="welcome-section">
  <h1>Hey I am Mimic</h1>
  <h4>a web developer</h4>
</section>

【讨论】:

  • 在导航栏上看不到这个的原因是因为它是一个固定的元素。如果您将其设置为相对,您应该会看到它也会显示边距。
猜你喜欢
  • 1970-01-01
  • 2011-08-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2022-01-21
  • 2010-11-03
  • 1970-01-01
  • 2012-02-12
相关资源
最近更新 更多