CSS居中的多种方法

1.水平居中:text-align 与 inline-block 的配合

<div id = "div_center_align">
<div id = "div_center_test"></div>
</div>
#div_center_align {
text-align: center
}
#div_center_test {
border:1px solid #ccc;
background-color: #ff2c42;
display: inline-block;
height: 10em;
width: 10em;
}
HTML 中在想要居中的元素外面套了一个父元素,然后在 CSS 中将父元素的 text-align 属性设为 center,接下来将子元素的 display 属性设为 inline-block 就可以水平居中了。

2.水平居中:通过 margin 实现

<div id = "div_center_margin"></div>
#div_center_margin {
width: 10em;
height: 10em;
border: 1px solid #ccc;
background-color: #ff2c42;
margin: 0 auto;
}
通过 margin 实现连父元素都不用套了,直接 margin: 0 auto; 搞定,对,就是这么简单快捷,恐怕是居中最常用的方法了吧.

3.垂直居中

<div id="div_center_margin02">
<div id="div_center_test"></div>
</div>
#div_center_margin02 {
position: relative;
background-color: #ff2c42;
height: 20em;
width: 50em;
}
#div_center_test {
border:1px solid #ccc;
background-color: #4053ff;
height: 10em;
width: 10em;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
  • 子元素 div 绝对定位
  • 父元素需要被定位
  • 子元素 top、bottom、left、right 四个位置值均为 0
  • 子元素 margin: auto;

 

4.垂直居中

  .content {

            width: 300px;
            height: 300px;
            background: orange;
            margin: 0 auto; /*水平居中*/
            position: relative; /*脱离文档流*/
            top: 50%; /*偏移*/
/*
除了可以使用margin-top把div往上偏移之外,CSS3的transform属性也可以实现这个功能,通过设置div的transform: translateY(-50%),意思是使得div向上平移(translate)自身高度的一半(50%)。
*/
transform: translateY(-50%);或margin-top:-150px;

     }

5.水平垂直居中:CSS3新属性FLEX

<div id="div_center_flex">
<div class="div_center_test"></div>
<div class="div_center_test"></div>
</div>
#div_center_flex {
display: flex;
display: -webkit-flex;
align-items: center; /*垂直居中*/
-webkit-align-items: /* center; */
justify-content: center; /*水平居中*/
-webkit-justify-content: center;
height: 20em;
width: 50em;
background-color: #ff2c42;
}
.div_center_test {
border:1px solid #ccc;
background-color: #4053FF;
height: 10em;
width: 10em;
}

使用 flex 容器布局实现水平垂直居中的关键点在于:

父元素 display 属性设为 flex

垂直布局的属性是 align-items,设为 center 时便垂直居中

水平布局的属性是 justify-content,设为 center 时水平居中

子元素弹性居中,增加子元素也不会有影响

6.通过一起使用 box-align 和 box-pack 属性,对 div 框的子元素进行居中:

 

.parent{
width: 300px;
height: 300px;
border: 1px solid black;

/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;


/* Safari, Chrome, and Opera */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;


/* W3C */
display:box;
box-pack:center;
box-align:center;
}
.child
{
width:100px;
height:100px;
border:1px solid black;
}

7.通过一起使用 display:flex 和 margin: auto属性,对 div 框的子元素进行居中:

.parent{

  border: 1px solid #ccc;
  width: 200px;
  height: 200px;
  display: flex;
}
.child{
  border: 1px solid #888;
  width: 100px;
  height: 100px;
  margin: auto;
}

 
posted @ 2016-01-22 11:06  有你便是晴天  阅读(280)  评论(0编辑  收藏  举报