25.css经典布局—粘连(css sticky footer)布局

1.什么是粘连布局(css sticky footer)

1.当main的高度足够长的时候,紧跟在<\main>后面的元素<\footer>会跟在其后面;
2.当<\main>元素比较短的时候(比如小于屏幕的高度),我们期望这个<\footer>元素能够“粘连”在屏幕的底部。
在这里插入图片描述
3.三个组成部分:wrap容器,main内容,footer脚部
方法一:footer 上用负的 margin-top
在内容外面需要额外包一层元素(wrap)来让它产生对应的 padding-bottom。是为了防止负 margin 导致 footer 覆盖任何实际内容。

//html结构
<body>
<div id="wrap">
	<div id="main">
		main<br/>
		main<br/>
	</div>
</div>
<div id="footer"></div>
</body>

//css样式
html, body {
  height: 100%;
  margin: 0;
}
#wrap{
	width: 100%;
    min-height: 100%;
}
/*内容区需要让出一部分区域,防止内容被盖住*/
#main{
    padding-bottom: 30px;
}
//wrap包裹内容的最小高度是100%,此时将footer的部分通过margin-top拉上去30px。
#footer{
    width: 100%;
    height: 30px;
    background-color: yellow;
    margin-top: -30px;
}

方法二:负margin-bottom
用一个元素将除了 footer 之外的其他内容包起来。给它设一个负的 margin-bottom,让它正好等于 footer 的高度。这是一个最基本的方法。

<body>
  <div class="wrapper">
      content
    <div class="push"></div>
  </div>
  <footer class="footer"></footer>
</body>

//css样式
html, body {
  height: 100%;
  margin: 0;
}
.wrapper {
  min-height: 100%;
  margin-bottom: -50px;
}
.footer,
.push {
  height: 50px;
}

方法三:flex布局
Web 设计中固定高度通常都不好,内容可能改变,我们需要footer灵活性。固定高度通常要被亮红灯。使用 flexbox 来实现粘连 footer 不仅不需要任何额外的元素,还可以支持 footer 可变高度。
/html结构

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

//css样式
html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
}
.footer{
	height: 50px;
    background-color: red;
}

甚至可以添加一个 header 到 .content 前面或者其他更多内容到后面。使用 flexbox 的诀窍是:
设置 flex: 1 在你希望自动填充窗口空间的子元素上(在我们的例子里是 .content 元素)。
可以设置 margin-top:auto 来让子元素尽可能远离它前面的元素(或者根据需要选择任意一个方向的 margin)。(上面的 flex:1 也可以用 margin-bottom:auto,内容垂直居中可以用margin:auto 0,flex 布局很奇妙吧)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值