CSS 弹性容器

该文章为英文原文译文及一些自己的拙见
墙裂推荐读原文
浏览原文请戳这里 : CSS-STRICKS

弹性布局 (Flexbox Layout)

什么是弹性布局

Flexbox Layout 模块旨在提供一种更为有效的方式来对容器(container)中的每一项(item)进行布置、对齐和空间分配,即使是在其尺寸未知或动态变化的情况下也能很好的发挥作用。

弹性布局的主要思想是赋予容器(container)改变内部每一项的长宽来更好的适应各种尺寸的屏幕(手机、平板或是台式显示器)。一个设置了flex属性的容器(container)可以对其内部的项(item)进行扩大来更好填充可用空间,或是缩小防止溢出。

重要的是,一般布局指基于垂直的块元素(block)和基于水平的行内元素(inline),弹性布局与一般布局不同的是它与方向无关。虽然一般布局也能很好地规划页面,但它缺乏在页面或元素发生旋转、改变大小时的灵活性。

容器和内部项的属性

弹性布局实为一种模型而非一个属性,其中包含了容器的属性和容器中每一项的属性。

下图阐释了弹性布局的主要思想 alt

在弹性布局中,容器内部的项(item)的布置方式基于主轴(main axis)或是交叉轴(cross axis)其中之一。

名称 备注
主轴(main axis) 主轴是内部项在布局是最主要遵循的轴,不一定是水平方向,其方向基于属性flex-direction的值
主轴起始点(main start) 在容器内布局的项从起始点开始
主轴结束点(main end) 截止到结束点
主轴尺寸(main size) 如图
交叉轴(cross axis) 始终保持与主轴垂直,即不一定是竖直方向
 交叉轴起始点(cross start)  内部项在交叉轴上排列的起点
 交叉轴结束点(cross end)  和终点
 交叉轴尺寸(cross size)  如图

弹性布局的属性

弹性布局的属性分为容器的属性,和其内部每一项的属性。

容器的属性
在想要使用弹性布局的元素上加上如下代码

CSS .container{ display: flex; /* 或者 inline-flex */ }

  • flex-direction

    CSS .container { flex-direction: row | row-reverse | column | column-reverse; }

    即内部项的排列方向,flex-direction 设置为 row-reverse 则会从一行的靠右边开始布置,而非是靠左布置。

    alt

备注
row(默认) 在设置了direction:ltr的元素上从左到右排列,在设置了direction:rtl元素上从右到左排列
row-reverse 在设置了direction:ltr的元素上从右到左排列,在设置了direction:rtl元素上从左到右排列
column row相同,但从上到下
column-reverse row-reverse相同,但从下到上
  • flex-wrap

    `CSS .container{ flex-wrap: nowrap | wrap | wrap-reverse; }

    `

    内部项的换行方式。

备注
nowrap(默认) 所有项目排成一行,不换行
wrap 换行,从上向下排
wrap-reverse 换行,从下向上排
  • flex-flow

    CSS .container{ flex-flow: <‘flex-direction’> || <‘flex-wrap’>; }

    属性flex-directionflex-wrap的简写整合版。

    CSS .container{ flex-flow: row-reverse wrap; } .container{ flex-direction: row-reverse; flex-wrap: nowrap; } // 两者写法效果等同 默认值为两者的默认值,即 row nowrap

  • justify-content

    CSS .container { justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly; }

    内部项在沿着主轴方向上的对齐方式和间距。

    alt

  • align-items

    CSS .container { align-items: flex-start | flex-end | center | baseline | stretch; }

    内部项在沿着交叉轴方向上的对齐方式。

    alt

  • align-content

    CSS .container { align-content: flex-start | flex-end | center | space-between | space-around | stretch; }

    该属性定义了多行情况下,沿交叉轴方向有剩余空间时,各行空间的分配情况,就如同竖直版的justify-content属性。

    alt

内部项的属性

to be continue

猜你喜欢

转载自www.cnblogs.com/number-project/p/9002175.html