CCS3 伸缩盒模型(最新)

CSS3伸缩盒对使用响应式布局的网站的开发带来了很好的实现方式。它可以在不使用浮动(float)和定位(position)的情况下实现块级(block)元素的水平排列。并且可以 把父元素的宽度按照比例分配子元素,闲话不多少直接看例子。

 

1、要实现伸缩盒模式必须给父元素设置:display:flex (老版本display:box 需要加对应的浏览器前缀),实现伸缩盒模式的显示方式。

2、通过设置子元素的flex-grow属性来分配比例

1 <div id="parent">
2     <div id="child1">01</div>
3     <div id="child2">02</div>
4     <div id="child3">03</div>
5 </div>

 1 #parent{
 2     width:1000px;
 3     height:200px;
 4     display:flex; /* 子元素水平排列 */
 5 }
 6 #parent div{
 7     font-size:100px;
 8     line-height:200px;
 9     text-align:center;
10 }
11 #child1{
12     width:200px;
13     background-color:orange;
14 }
15 #child2{
16     flex-grow:1; /* 分配比例因子 */   
17     background-color:pink;
18 }
19 #child3{
20     flex-grow:3; /* 分配比例因子 */ 
21   background-color:green;
22  }

分析:parent 的宽度为1000px,child1的宽度为200px,所以child2 + child3 = 1000 - 200 = 800px,因为 child2 和 child3 都设置了flex-grow:1 和 flex-grow:3;所以child2 的宽度为 800 * 1/(1+3) = 200px,child3 的宽度为 800 * 3/(1+3)。

注意:1、如果子元素有固定的宽度,其他子元素按比例分配剩余的宽度 即:1000 - 200 = 800px;

   2、均分总数为各个子元素中flex-grow属性值的和 即:1 + 3 = 4,各元素的宽度比例为 flex-grow / (flex-grow的总和) 即:1/(1+3),3/(1+3);

 排列方向

flex-direction 属性用来设置子元素的排列方向,该属性总共有四个参数:row (横向) row-reverse (横向反转) column (纵向) column-reverse (纵向反转)

1 #parent{
2     width:1000px;
3     height:200px;
4     display:flex;
5     flex-direction:row-reverse;/* 横向反转 */
6 }

 对齐方式

justify-content 属性用来定义子元素的对齐方式,其属性值包括:flex-start (左对齐) flex-end (右对齐) center (中间对齐)

 1 #parent{
 2     width:1000px;
 3     height:200px;
 4     display:flex;
 5     justify-content:center; /* 中间对齐 */
 6     background-color:#ff0;
 7     flex-direction:row-reverse;
 8 }
 9 #parent div{
10     font-size:100px;
11     line-height:200px;
12     text-align:center;
13 }
14 #child1{
15     width:200px;
16     background-color:orange;
17 }
18 #child2{
19     width:200px;
20     background-color:pink;
21 }
22 #child3{
23     width:200px;
24     background-color:green;
25 }

align-items 垂直对齐  flex-start (垂直顶对齐) flex-end (垂直底对齐) center (垂直居中对齐)

 1 #parent{
 2     width:1000px;
 3     height:200px;
 4     display:flex;
 5     align-items:flex-end;
 6     justify-content:center;
 7     background-color:#ff0;
 8     flex-direction:row-reverse;
 9 }
10 #parent div{
11     font-size:100px;
12     line-height:200px;
13     text-align:center;
14 }
15 #child1{
16     width:200px;
17     background-color:orange;
18 }
19 #parent #child2{
20     width:200px;
21     height:100px;
22     font-size:50px;
23     line-height:100px;
24     background-color:pink;
25 }
26 #child3{
27     width:200px;
28     background-color:green;
29 }

posted on 2015-01-21 11:58  liangshanbo  阅读(730)  评论(0)    收藏  举报

导航