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

CSS垂直居中方式

时间:2016-04-03 18:52:43      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

因为工作中有用到,所以找了几种。

1、

body {
height: 100%;
width: 100%;
}

.Absolute-Center {
background-color: greenyellow;
width: 300px;
height: 300px;

position: absolute;
top: 50%;
left: 50%;

margin-top: -150px;
margin-left: -150px;

}

第一种方式比较常见,先将需要垂直居中的元素进行绝对定位,然后用设置top和left各为50%,在利用margin将他们偏移 -1/2的width和height 就行了。

这种方式比较方便,但必须知道元素的长宽才行。

2、

body {
height: 100%;
width: 100%;
}

.Absolute-Center {
background-color: greenyellow;
width: 50%;
height: 50%;

position: absolute;
top: 50%;
left: 50%;

transform: translate(-50%,-50%);
}

第二种方式则用到了 tranform属性中的translate进行偏移,这种做的好处就是不用知道元素的长宽,只需要设置 -50% 即可

3、

body {
position: absolute;
height: 100%;
width: 100%;

display: flex;
align-items: center;
justify-content: center;
}

.Absolute-Center {
background-color: greenyellow;
width: 50%;
height: 50%;
}

 第三种则用到了 CSS3的flex来进行垂直居中 将父元素display为flex 然后设置 align-items和justify-content都为center即可

接下来 安利一个网站 里面有各种详细的垂直居中方式

https://css-tricks.com/centering-css-complete-guide/

CSS垂直居中方式

标签:

原文地址:http://www.cnblogs.com/fao931013/p/5350299.html

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