常见布局—弹性布局

2020-04-20  本文已影响0人  坏丶毛病

在常见的布局中,通常有一部分是固定高度,而其他部分是剩余大小分配的,这种情况我们可以使用弹性布局。

说到弹性布局,就得介绍一下css属性中的弹性盒——display:flex

它分为主轴和交叉轴两个方向,没有固定的方向,默认主轴是X轴,交叉轴是Y轴,也可以通过属性 flex-direction: column来设置主轴为Y轴

主轴是X轴,意味着它会把子元素横向排列,所有子元素都到一行,Y轴也就是反过来的。

主轴对齐方式——justify-content: center;(这里我选择的是居中对齐)

交叉轴对齐方式——align-items: center;(这里我选择的是居中对齐)

那我们来实现几个小例子:

(1)、设置两个元素横向排列

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        html,body{
            width: 100%;
            height: 100%;
        }
        .box{
            width: 100%;
            height: 300px;
            display: flex;
        }
        .left{
            width: 50%;
            height: 300px;
            background: lightblue;
        }
        .right{
            width: 50%;
            height: 300px;
            background: pink;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="left"></div>
        <div class="right"></div>
    </div>
</body>
</html>

效果:

image

(2)、设置上下两部分,上部固定高度,下部占剩余部分,其中下部左边固定,右边占剩余部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        html,body{
            width: 100%;
            height: 100%;
        }
        .box{
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .top{
            width: 100%;
            height: 200px;
            background: lightblue;
        }
        .content{
            flex: 1;
            display: flex;
        }
        .left{
            width: 300px;
            height: 100%;
            background: pink;
        }
        .right{
            flex: 1;
            background: orange;
        }
    </style>
</head>
<body>
    <div class="box">

        <div class="top"></div>

        <div class="content">
            <div class="left"></div>
            <div class="right"></div>
        </div>

    </div>
</body>
</html>

这里解释一下,flex是在父元素中有 display:flex的情况下,这个元素占父元素的大小减去其他子元素的大小,即剩余全部大小

效果:

image

弹性盒还有很多属性,这里就不一一介绍了,如果有需要,大家可以自行去了解。

如有疑问,也可以咨询博主。

好了,这次就介绍到这里。

如有问题,请指出,接受批评。

上一篇 下一篇

猜你喜欢

热点阅读