You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

基于Bootstrap 3实现高度自适应粘性页脚的方法问询

实现Bootstrap 3动态高度图片组成的粘性页脚

刚好碰到过类似的场景,因为页脚高度是随图片缩放动态变化的,常规固定高度的粘性页脚方案完全不适用,这里给你两种靠谱的解决办法,优先推荐第一种,不用写JS更省心:

方法一:用CSS Flexbox布局(推荐)

Flexbox可以完美适配动态高度的元素,而且现在主流浏览器都支持,哪怕是Bootstrap 3也能直接用。

步骤1:调整HTML结构

把页面主体内容和页脚分开,让body作为flex容器:

<html>
  <body>
    <!-- 原来的页面内容(包括你的container-responsive)放在这里 -->
    <div class="container-responsive">
      <!-- 你的页面内容 -->
    </div>

    <!-- 页脚部分保留你原来的结构 -->
    <footer>
      <div class="row no-gutter">
        <div class="col-md-4 col-sm-12 col-lg-4 no-padding">
          <a href="..."><img src="..." class="img-responsive" /></a>
        </div>
        <div class="col-md-4 col-sm-12 col-lg-4 no-padding">
          <a href="..."><img src="..." class="img-responsive" /></a>
        </div>
        <div class="col-md-4 col-sm-12 col-lg-4 no-padding">
          <a href="..."><img src="..." class="img-responsive" /></a>
        </div>
      </div>
    </footer>
  </body>
</html>

注意给图片加上Bootstrap的img-responsive类,确保图片能随宽度自动缩放,这样页脚高度就会跟着动态变化。

步骤2:添加自定义CSS

/* 让html和body占满整个视口高度 */
html {
  height: 100%;
}
body {
  min-height: 100%;
  /* 把body设为flex容器,垂直排列元素 */
  display: flex;
  flex-direction: column;
  margin: 0;
}

/* 让主体内容占满剩余空间,把页脚推到底部 */
.container-responsive {
  flex: 1;
}

/* 处理你用到的no-gutter和no-padding类,避免额外间距影响布局 */
.no-gutter {
  margin-left: 0;
  margin-right: 0;
}
.no-gutter > [class*="col-"] {
  padding-left: 0;
  padding-right: 0;
}
.no-padding {
  padding: 0 !important;
}

这样不管页脚高度怎么变,flex都会自动把它固定在页面底部:内容不够长时,页脚在视口底部;内容超过视口高度时,页脚会被推到内容最下方,不会覆盖内容。

方法二:用JS动态计算高度(备选)

如果需要兼容非常老旧的浏览器(比如IE9及以下),可以用JS动态计算页脚高度,调整body的内边距:

步骤1:添加基础CSS

html {
  position: relative;
  min-height: 100%;
}
body {
  /* 这个内边距会由JS动态设置,等于页脚高度 */
  margin-bottom: 0;
}
footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}

/* 同样处理间距问题 */
.no-gutter {
  margin-left: 0;
  margin-right: 0;
}
.no-gutter > [class*="col-"] {
  padding-left: 0;
  padding-right: 0;
}
.no-padding {
  padding: 0 !important;
}

步骤2:添加JS代码(用jQuery,Bootstrap 3默认依赖它)

// 计算页脚高度并设置body的padding-bottom
function adjustFooter() {
  var footerHeight = $('footer').outerHeight();
  $('body').css('padding-bottom', footerHeight + 'px');
}

// 页面加载和窗口resize时都要重新计算
$(document).ready(adjustFooter);
$(window).resize(adjustFooter);

这种方法需要监听窗口大小变化,每次都重新计算页脚高度,确保内容不会被页脚挡住。


内容的提问来源于stack exchange,提问作者Damien

火山引擎 最新活动