布局解决方案之居中布局

1、水平居中布局(父容器和子容器宽度都不是固定的)

方案1:利用inline-block 和 text-align,设置父容器的text-align="center",即父容器内的inline元素居中显示,再把子容器display设置成inline-block即可。

CSS代码:

1 .parent{
2     text-align: center;
3 }
4 .child{
5     background-color: red;
6     display: inline-block; 在IE6以及低版本浏览器中模拟inline-block:display:inline;zoom:1
7 }

方案2:利用table 和 margin,设置子容器的display为table,margin:0 auto,因为display:table宽度也是随着内容而变化的。

CSS代码:

1 .child{
2     display: table;
3     margin: 0 auto;
4     background-color: red;
5 }

方案3:利用absoulte 和

 

1 .parent{
2     position: relative;
3 }
4 .child{
5     position: absolute;
6     left: 50%;
7     transform:translateX(-50%);
8     background-color: blue;
9 }

方案4:利用flex 和 justify-content,仅仅设置父容器的display和justify-content属性即可。

CSS代码:

 1 .parent{ 2 display: flex; 3 justify-content:center; 4 } 

以上所有CSS代码的应用场景HTML代码如下:

1 <div class="parent">
2     <div class="child">DEMO</div>
3 </div>

2、垂直居中布局(父容器和子容器的高度都不是固定的)

方案1:利用table-cell 和 vertical-align来实现。

CSS代码:

 1 .parent{ 2 display: table-cell; 3 vertical-align: middle; 4 } 

方案2:利用absoulte 和 transform来实现。

CSS代码:

1 .parent{
2     position: relative;
3 }
4 .child{
5     background-color: red;
6     position: absolute;
7     top: 50%;
8     transform:translateY(-50%);
9 }

方案3:利用flex 和 align-items来实现。

 1 .parent{ 2 display: flex; 3 align-items:center; 4 } 

以上所有CSS代码的应用场景HTML代码如下:

1 <div class="parent">
2     <div class="child">DEMO</div>
3 </div>

3、水平和垂直都居中(父容器和子容器的宽度和高度都不是固定的)

方案1:利用inline-block、text-align、table-cell 和 vertical-align来实现。

1 .parent{
2     text-align: center;
3     display: table-cell;
4     vertical-align: middle;
5 }
6 .child{
7     display: inline-block;
8 }

方案2:利用absolute 和 transform来实现。

CSS代码:

1 .parent{
2     position: relative;
3 }
4 .child{
5     position: absolute;
6     left: 50%;
7     top:50%;
8     transform:translate(-50%,-50%);
9 }

方案3:利用flex、justify-content 和 align-items来实现。

CSS代码:

1 .parent{
2     display: flex;
3     justify-content:center;
4     align-items:center;
5 }

以上所有CSS代码的应用场景HTML代码如下:

1 <div class="parent">
2     <div class="child">DEMO</div>
3 </div>

 

posted @ 2015-08-17 17:30  yxz_turing  阅读(293)  评论(0编辑  收藏  举报