首页 > Web开发 > 详细

CSS居中的多种方法

时间:2016-01-22 13:40:15      阅读:221      评论:0      收藏:0      [点我收藏+]

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.水平垂直居中: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 时水平居中

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

 
 
 

CSS居中的多种方法

原文:http://www.cnblogs.com/liangxuru/p/5150549.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!