圣杯布局的实现:flex布局版本

132 阅读1分钟

前言:

圣杯布局是css之中的经典布局,它指的是两边固定,中间自适应的三栏布局,同时中间的内容盒子需要优先加载。

一般的解决方式是利用浮动方法和内容盒子的内外边距的设置来完成内容盒子的偏移,来获取所需要的效果。在本文中将会介绍使用flex完成的版本。

具体思路

  1. 将外层的content盒子的display属性设置为flex,设置justify-content使得盒子两边对齐
  2. 使用calc()方法设置中间盒子的宽度
  3. 通过order属性定义三个盒子的排列顺序

实现效果

9ff9a0e3ad1c9cbcda68e1b9eec89b0.png

完整代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
                .layout {
                        width: 100%;
                        height: 100%;
                        font-size: 25px;
                        text-align: center;
                }

                .header {
                        width: 100%;
                        height: 100px;
                        background-color: red;
                        line-height: 100px;
                }

                .content {
                        width: 100%;
                        height:400px;	
                        background-color: wheat;
                        display: flex;
                        justify-content: space-between;
                }

                .middle {
                        width: calc(100% - 400px);
                        height: 100%;
                        background-color: yellow;
                        order:2;
                }
                .left {
                        width: 200px;
                        height: 100%;
                        background-color: aqua;
                        order:1
                }

                .right {
                        width: 200px;
                        height: 100%;
                        background-color: orange;
                        order:3;
                }

                .footer {
                        width: 100%;
                        height: 100px;
                        background-color: green;
                        line-height: 100px;
                }
        </style>
    </head>
    <body>
        <div class="layout">
                <div class="header">顶部栏</div>
                <div class="content">
                        <div class="middle">middle</div>
                        <div class="left">left</div>
                        <div class="right">right</div>
                </div>
                <div class="footer">底部栏</div>
        </div>
    </body>
</html>