css弹性盒子|青训营笔记

41 阅读2分钟

这是我参与 [第五届青训营] 伴学笔记创作活动的第二天,下面是我学习css中弹性盒子的笔记。

定义

弹性盒子是 css3 的一种新的布局模式,提供了一种更加高效的方式来对一个容器中的子元素进行排列、对齐和分配空白空间。

弹性盒子内容

  • 弹性容器(Flex container)
  • 弹性子元素(Flex item) 弹性容器内包含一个或多个弹性子元素,如下面示例:
<div class="flex-container">
  <div class="flex-item">flex item 1</div>
  <div class="flex-item">flex item 2</div>
  <div class="flex-item">flex item 3</div>
</div>
<style>
  .flex-container {
    display: flex;
    width: 400px;
    height: 250px;
    background-color: #666;
 }
  .flex-item {
    background-color: red;
    width: 100px;
    height: 100px;
    margin: 10px;
 }
</style>

ps:默认弹性盒子里的内容横向摆放。

父元素上的属性

display属性

display:flex:开启弹性盒子属性

flex-direaction属性

flex-direction 属性指定了弹性子元素在父容器中的位置

  • row:横向从左至右排列
  • row-reverse:反转横向排列
  • column:纵向排列
  • column-reverse:反转纵向排列

justfy-content属性

内容对齐(justify-content)属性应用在弹性容器上,把弹性项沿着弹性容器的主轴线(main axis)对齐。 justify-content: flex-start | flex-end | center

align-items属性

align-items 设置或检索弹性盒子元素在侧轴(纵轴)方向上的对齐方式。 align-items: flex-start | flex-end | center

子元素上的属性

flex-grow: 根据弹性盒子元素所设置的扩展因子作为比率来分配剩余空间。默认为0,即如果存在剩余空间,也不放大。 flex: 根据盒子所设置的扩展因子作为比率来分配父元素所有的空间

示例:

<div class="container">
    <div class="box1"></div>
    <div class="box2"></div>
    <div class="box3"></div>
</div>
<style>
    .container{
        width: 400px;
        height: 400px;
        background-color: #ccc;
        display: flex;
        align-items: center;
    }

    .box1{
        width: 100px;
        height: 100px;
        background-color: red;
        flex: 2;
    }

    .box2{
        width: 100px;
        height: 100px;
        background-color: green;
        flex: 1;
    }

    .box3{
        width: 100px;
        height: 100px;
        background-color: blue;
        flex: 1;
    }
</style>

效果:

flex:

flex-grow:

总结

弹性盒子可以设置一个容器中子元素的排列、对齐和分配空白空间,可以使页面适应不同的屏幕大小以及设备类型,确保元素拥有恰当的行为。