传统的网页布局方案是基于盒子模型,依赖display、position、float等属性,这种布局方式对于特殊的布局来说比较难以实现,例如垂直居中等。
2009年,W3C提出了一种新的方案——Flex布局(CSS FlexBox),也就是弹性布局,用来为盒子模型提供最大的灵活性,成为了移动端Web开发的首选方案。
兼容性方面也得到了大多数浏览器的兼容支持,可以放心使用。
使用
任何容器都可以指定为Flex布局,Webkit内核的浏览器,需要加上-webkit-的前缀。
.box{ display: flex; display: -webkit-flex; }
行内元素也可以使用Flex布局。
.box{ display: inline-flex; }
当元素设置为flex布局后,子元素的float、clear、verti-align属性会失效。
容器属性
flex-direction
flex-direction属性决定子元素的排列方向,可取值为:
- row(默认值,从左向右)
- row-reverse(从右向左)
- column(从上到下)
- column-reverse(从下到上)
flex-wrap
flex-direction属性决定子元素如果排满一排后如何换行,可取值为:
- nowrap(默认值,不换行,自动缩小盒子放在一排)
- wrap(普通换行)
- wrap-reverse(换行并且第一行在下方)
flex-flow
flex-flow属性是flex-direction和flex-wrap的简写,默认属性为row nowrap,即横向排列不换行。
justify-content
justify-content属性决定了子元素的对齐方式,可选参数有:
- flex-start(默认值,左对齐)
- flex-end(右对齐)、center(居中)
- space-between(两端对齐,子元素之间间隔相等)
- space-around(子元素两侧间隔相等)
- space-evenly(子元素之间与两侧之间间隔相等)
align-items
align-items属性定义子元素在垂直轴向的排列方式,可选参数为:
- stretch(默认值,如果子元素未设置高度或者高度为auto,则竖向拉伸占满整个容器)
- flex-start(子元素紧贴容器顶部)
- flex-end(子元素紧贴容器底部)
- center(垂直居中)
- baseline(以第一行文字的基线对齐)
align-content
align-content属性与justify-content属性类似,用于控制多行子元素每一行之间的垂直排列方式。可选值有:
- stretch(默认值,如果子元素未设置高度或者高度为auto,则竖向拉伸使多行占满整个容器)
- flex-start(顶部对齐)
- center(居中,上下方留空)
- flex-end(底部对齐)
- space-between(子元素首尾行紧贴容器上下边缘,其他行间隔相等)
- space-around(子元素上下两侧间隔相等)
- space-evenly(元素上下两侧之间间隔与容器边缘间隔相等)
子元素属性
order
order属性用于更改项目排列顺序,默认值为0,数值越小,排列顺序越靠前,数值相同则按书写顺序排列。
flex-grow
flex-grow属性用于决定当有剩余空间的时候是否将子元素拉伸,默认为0不放大。
flex-shrink
flex-shrink属性用于决定项目空间不足时是否缩小(nowrap不换行时),默认值为1缩小。
flex-basis
flex-basis属性用于设置子元素宽度,默认值为auto,权重比width高会覆盖width。
flex
flex为复合属性,是flex-grow、flex-shrink、flex-basis三个属性的简写,默认值为0 1 auto。
可以设置为auto(等分放大缩小,1 1 auto)或者none(不放大但等分缩小,0 0 auto)。
align-self
align-self属性用于让子元素拥有与其他子元素不同的对齐方式,可取值为:
- auto(默认值,继承父容器的align-items属性)
- stretch(没有父元素时的默认值)
- flex-start
- flex-end
- center
- baseline
世上有两样东西不可直视,
一是太阳,
二是人心。
《白夜行》——东野圭吾
评论
425911 469390Can anyone help me out? It will probably be significantly appreciated. 143887
460814 48004Im agitated all these article directories. It sure would be nice to have every write-up directory that instantly accepts articles. 71523
196054 228184Over and over again I think about these issue. As a matter of fact it was not even yesterday that I last thought about it. To be honest, what is your thought though? 239238
760596 940208Hi, you used to write outstanding articles, but the last several posts have been kinda boring I miss your tremendous posts. Past few posts are just a bit out of track! 325778
471615 679065This internet site is my inspiration , really superb layout and perfect subject matter. 224828
774762 79235Paper rolls quite wonderful read you know alot about this subject i see! 328