【问题标题】:Fixed Sidebar with margin top and margin bottom固定侧边栏,顶部边距和底部边距
【发布时间】:2021-01-30 06:02:40
【问题描述】:

基本上,我尝试构建一个侧边栏,它在顶部和底部都有一些空间,但我无法到达底部。这是一张照片sidebar has top spaces but not bottom

这是我的css代码

.sidebar {
  position: fixed;
  top: 14px;
  left: 20px;
  //bottom: 14px;
  width: 7.375rem;
  height: 100%;
  // margin-bottom: 14px;
  border-radius: 1.8125rem;
  background-color: blue;
  z-index: 100;
}

我怎样才能像侧边栏一样在底部也有空间作为顶部。我试图给底部一个边距并设置底部,但我没有得到它。

【问题讨论】:

  • 嘿伙计!您是否尝试过添加填充? padding-bottom: 14px;
  • 在没有看到整个页面的上下文的情况下给出一个非常好的答案是很棘手的。
  • 显示更多代码,请

标签: html css


【解决方案1】:

可以简单地添加一个额外的容器作为包装容器并使用padding

使用calc 意味着您必须严格指定您希望拥有的顶部/底部数量。

这是一个简单的例子:

HTML:

<div class="wrap">
  <div class="sidebar"></div>
</div>

CSS:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wrap {
  width: 7.375rem;
  left: 20px;
  position: fixed;
  height: 100vh;
  z-index: 100;
  padding: 20px 0;
}

.sidebar {
  border-radius: 1.8125rem;
  background-color: blue;
  height: 100%;
}

这样,wrap 类的容器设置了内部容器sidebarpadding 的限制,在wrap 容器中,将内部容器从顶部和底部限制为20px . box-sizing: border-box 是 IMPOSTANT tho,要么将其应用于所有内容,例如我的示例,要么只是 wrap 类。没有它,height: 100% 的子元素将占用整个父元素的高度 + 40px 的顶部和底部填充。这与 calc 自动执行的操作类似。

【讨论】:

    【解决方案2】:

    将高度设置为 100% 会导致问题。

    您可以尝试使用 calc,将高度设置为 100%,减去所需的顶部和底部空间,例如:

    height: calc(100% - 28px);
    

    【讨论】:

    • 非常感谢。这很棒。我怎么会想不到这一点。非常感谢