绝对定位 div 和底部 属性 的边距顶部

Margin-top for absolute positioned div with bottom property

我正在创建一个 div 作为页脚:

<div class="content">blah blah blah</div>
<div class="content">more content</div>
<div class="content">even more content</div>
<div id="footer">blah blah blah</div>

页脚的CSS如下:

#footer{
    height: 50px;
    display: block;
    position: absolute;
    right: 0;
    left: 0;
    bottom: 0;
}

那么如何在 contentfooter 之间留下 50px space?我试过在两者之间添加 spacer div 但没有成功。 spacer div 需要大于 content 的高度才能生效。我试过 margin-top#footer,但没有用,但我不想要 contentmargin-bottom,因为内容容器是多个。为 content 设置底部边距会破坏它们的呈现方式。感谢您的帮助。

P.S。这不是 Set position absolute and margin.

的副本

编辑:根据您在下面的评论,您正在寻找的是静态页脚

#footer{
    height: 50px;
    display: block;
    margin-top: 50px;
}

我是个菜鸟,无法评论更多信息:| .我假设您可能正在尝试实现页脚始终出现在页面底部的 fixed / sticky footer?如果您可以提供一个示例来说明您要达到的效果,我很乐意使用更具体的信息来编辑我的答案。

无论如何,因为您使用的是绝对定位,所以该元素已脱离文档流,不会影响页面上的任何其他元素。这意味着边距不起作用。固定定位也是如此,如果你在做一个basic sticky footer.

,这就是你真正想要的。

如果您希望边距对元素有任何影响,您需要将元素显示 属性 设置为块级元素(块、table、内联块等)和它定位到静态(默认)或相对。

稳健的粘性页脚最干净的方法是使用弹性框。注意使用语义 html 标签和 类 而不是 id 的

<style>
     /**
     * 1. Avoid the IE 10-11 `min-height` bug.
     * 2. Set `flex-shrink` to `0` to prevent Chrome, Opera, and Safari from
     *    letting these items shrink to smaller than their content's default
     *    minimum size.
     */
    .site {
        display: flex;
        flex-direction: column;
        height: 100vh; /* 1 */
    }
    .header,
    .footer {
        margin-top: 50px;
        flex-shrink: 0; /* 2 */
    }
    .content {
        flex: 1 0 auto; /* 2 */
    }
</style>

<body class="site">
    <header class="header">…</header>
    <main class="content">…</main>
    <footer class="footer">…</footer>
</body>

由菲利普沃尔顿提供 http://philipwalton.com/articles/normalizing-cross-browser-flexbox-bugs/

请注意,这仅适用于较新的浏览器,因此如果您支持旧版本的 IE,则需要使用基于固定定位的粘性页脚,或者完全忘记粘性页脚。

好的,让我们试一试。

也许这对您有所帮助:

http://codepen.io/bbredewold/pen/avgZmj

如果您描述您想要实现的行为,包括页面在不同大小下应如何响应,将会有所帮助。或许你可以fork(copy)笔,做一些补充,帮助我们理解你的问题。

祝你好运!

.outside {
  position: absolute;
  overflow: scroll;
  background: #ccc;
  bottom: 100px;
  left: 0;
  right: 0;
  top: 0;
}
.content {
  outline: 1px solid blue;
}
#footer {
  outline: 1px solid red;
  background: #ccc;
  height: 50px;
  display: block;
  position: absolute;
  right: 0;
  left: 0;
  bottom: 0;
}
<div class="outside">
  <div class="content">blah blah blah</div>
  <div class="content">more content</div>
  <div class="content">even more content</div>
</div>

<div id="footer">blah blah blah</div>

是的,这样不行。因为您已经为#footer 指定了绝对位置,所以它的位置与文档中其他元素的位置无关。

两个没有关联的事物之间不会显示任何边距或填充量。