css
主页 > 网页 > css >

css把元素固定在容器底部的四种方式介绍

2022-06-19 | 酷站 | 点击:

前几天被人问,「如何把元素固定在容器底部」。(本来想直接把 demo 地址给他,结果没找到,那么今天我们来补一下)

Demo 地址:http://jsrun.net/vIzKp/edit

想法&思路

如果是页面底部,我们可以直接 position: fixed;bottom: 0; 基于浏览器定位直接实现。

但是他要的效果是基于父级容器,那么我们必须要使用其他手段来定位了

使用 flex 实现

calc 实现

如果不使用 flex ,那么我们可以用 calc 来减去 header 和 footer 空间。

1

2

3

4

5

6

7

8

9

<style>

    .demo3{

        position: relative;

    }

    .demo3 .content{

        overflow: auto;

        max-height: calc(100% - 40px);

    }

</style>

absolute 实现

如果 calc 兼容性不太好,那么还可以使用 absolute 将所有元素都脱离文档流。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<style>

    .demo4{

        position: relative;

    }

    .demo4 .header,.demo4 .footer{

        position: absolute;

        margin: 0;

        top:0;left:0 ;right:0;

    }

    .demo4 .footer{

        top: auto;

        bottom: 0;

    }

    .demo4 .content{

        overflow: auto;

        height: 100%;

        padding-top: 30px;

        padding-bottom: 30px;

        margin: 0;

        box-sizing: border-box;

    }

</style>

原文链接:
相关文章
最新更新