css实现圣杯布局的几种方法

61 阅读1分钟

先写结构:

<body>
    <div class="header"></div>
    <div class="father">
        <div class="left-son"></div>
        <div class="center"></div>
        <div class="right-son"></div>
    </div>
    <div class="footer"></div>
</body>

1.使用display:flex布局
核心是利用flex: 1来自动伸缩,填满中间空隙,flex: 1是由flex: grow; flex: shrink; flex: basis三个属性的简写

 .header{
    width: 100%;
    height: 30px;
    background-color: brown;
}
.footer{
    width: 100%;
    height: 30px;
    background-color: brown;
}
 .father{
     display: flex;
     height: 60px;
 }
 .left-son{
     width:50px;
     height: 100%;
 }
 .middle-son{
     height: 50px;
     flex: 1;
 }
 .right-son{
     width:50px;
     height: 100%;
 }

效果:

image.png

2.使用定位+padding
核心是使用子绝父相,定位到父盒子两边,而父盒子用padding给子盒子腾出位置

.father{
    position: relative;
    width: 100%;
    height: 60px;
    padding-left: 50px;
    padding-right: 50px;
    background-color: red;
    box-sizing: border-box;
}
.left-son{
    position: absolute;
    left: 0;
    top: 0;
    width: 50px;
    height: 100%;
    background-color: aqua;
}
.right-son{
    position: absolute;
    right: 0;
    top: 0;
    width: 50px;
    height: 100%;
    background-color: yellow;
}
.middle{
    height: 100%
    background-color: pink;
}

3.利用BFC+浮动 核心是利用左浮动右浮动自动放置在同一行两侧的特点,

//css
.father{
    height:50px;
    background-color: blue;
}
.left{
    float:left;
    width:50px;
    height:50px;
    background-color: pink;
}
.right{
    float:right;
    width:50px;
    height:50px;
    background-color: aqua
}
.center{
    height: 50px;
    background-color: green;
    overflow: hidden;
}

//html
<body>
    <div class="father">
        <div class="left-son"></div>
        <div class="right-son"></div>
        <div class="center"></div>
    </div>
</body>

image.png
4.利用grid属性

        .father {
            text-align: center;
            height: 100px;
            display: grid;
        }

        .left-son {
            grid-row: 2;
            grid-column: 1/2;
            background-color: aqua;
        }

        .center {
            grid-row: 2;
            grid-column: 2/4;
            background-color: pink;
        }

        .right-son {
            grid-row: 2;
            grid-column: 4/5;
            background-color: orange;
        }

image.png