码迷,mamicode.com
首页 > Web开发 > 详细

CSS元素水平垂直居中的方法

时间:2018-04-17 16:51:48      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:分配   select   cal   nbsp   relative   button   eve   说明   左右   

1.  元素水平居中

1.1  设置父元素的属性

text-align: center;

 

说明:此属性只针对父元素的子元素为内联元素时有效,比如:img,input,select,button等(行内元素,但表现上属于内联元素,可以设置宽度和高度),span需要将display属性设置为内联,并设置宽度和高度。

参考:MDN内联元素

1.2  设置元素自身边距属性

margin: 0 auto;
display: block;

说明:元素必须设置为块元素,通过margin属性自动分配左右边距达到居中效果

1.3  设置元素定位属性

position: relative; //父元素设置相对定位

position: absolute; //子元素设置绝对定位,并向左移动元素自身一半的长度
width:50px;
height: 50px;
left: 50%;
transform: translateX(-50%);

 

2.  元素垂直居中

2.1   设置元素定位属性,类似1.3

position: relative; //父元素设置相对定位

position: absolute; //子元素设置绝对定位,并向左移动元素自身一半的长度
width:50px;
height: 50px;
top: 50%;
transform: translateY(-50%);

2.2  通过table特性设置元素

display: table-cell;
vertical-align: middle;

说明:把内联或者行内元素伪装成单元格子元素,通过table标签的特性处理单元格,此方法对低版本的IE6/7不兼容

 

3.  元素水平垂直居中

3.1  设置元素定位属性,类似1.3

position: relative; //父元素设置相对定位

position: absolute; //子元素设置绝对定位,并向左向上移动元素自身一半的长度
width:50px;
height: 50px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);

3.2  根据元素的自动定位属性

position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width:50px;
height: 50px;

说明:此方法跟3.1类似,只是自动计算所有的margin值,以到达上下左右居中效果。

 

参考:https://www.cnblogs.com/zjjDaily/p/5952723.html

CSS元素水平垂直居中的方法

标签:分配   select   cal   nbsp   relative   button   eve   说明   左右   

原文地址:https://www.cnblogs.com/jolley/p/8867180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!