页脚位于页面底部或内容底部(以较低者为准)
P粉716228245
P粉716228245 2024-01-21 15:32:38
0
2
486

我有以下结构:

<body>
    <div id="main-wrapper">
        <header>
        </header>
        <nav>
        </nav>
        <article>
        </article>
        <footer>
        </footer>
    </div>
</body>

我使用 javascript 动态加载

中的内容。因此,
块的高度可能会发生变化。


我希望

块在内容较多时位于页面底部,或者在只有几行内容时位于浏览器窗口底部。


目前我可以选择其中之一...但不能两者都做。

有谁知道我该怎么做 - 让

粘贴到页面/内容的底部或屏幕的底部,具体取决于哪个较低。


P粉716228245
P粉716228245

全部回复(2)
P粉344355715

Ryan Fait 的粘性页脚是一个简单的解决方案,我过去曾多次使用过。

基本 HTML

<div class="wrapper">
    <div class="header">
        <h1>CSS Sticky Footer</h1>
    </div>
    <div class="content"></div>
    <div class="push"></div>
</div>
<div class="footer"></div>

CSS

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}

/*

Sticky Footer by Ryan Fait
http://ryanfait.com/

*/

将其翻译为类似于您已经得到的结果,大致如下:

HTML

<body>
    <div class="wrapper">
        <header>
        </header>
        <nav>
        </nav>
        <article>
        </article>
        <div class="push"></div>
    </div>
    <footer>
    </footer>
</body>

CSS:

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}

只是不要忘记更新包装边距上的负数以匹配页脚和推送 div 的高度。祝你好运!

P粉970736384

Ryan Fait 的粘性页脚 是非常好,但是我发现它缺乏基本结构*。


Flexbox 版本

如果您足够幸运,可以使用 Flexbox 而无需支持旧版浏览器,那么粘性页脚就会变得非常简单,并且支持动态调整大小的页脚。

使用 Flexbox 让页脚粘在底部的技巧是让同一容器中的其他元素垂直弯曲。它所需要的只是一个带有 display: flex 的全高包装元素和至少一个 flex 值大于 0 的同级元素: p> CSS:子>

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#main-wrapper {
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

article {
  flex: 1;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#main-wrapper {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  min-height: 100%;
}
article {
  -webkit-box-flex: 1;
      -ms-flex: 1;
          flex: 1;
}
header {
  background-color: #F00;
}
nav {
  background-color: #FF0;
}
article {
  background-color: #0F0;
}
footer {
  background-color: #00F;
}
<div id="main-wrapper">
   <header>
     here be header
   </header>
   <nav>
   </nav>
   <article>
     here be content
   </article>
   <footer>
     here be footer
   </footer>
</div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板