固定边栏顶部边距和底部边距

时间:2021-01-29 21:17:27

标签: html css

基本上我试图建立一个侧边栏,它的顶部和底部都有一些空间,但我无法到达底部。这是一张照片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;
}

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

2 个答案:

答案 0 :(得分: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 自动执行的操作类似。

答案 1 :(得分:0)

将高度设置为 100% 会导致这里出现问题。

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

height: calc(100% - 28px);