Home

Written by Mary Ma, and build some interesting tools .

如何实现水平居中 & 垂直居中

2017-08-13

感觉现在的自己已经超级懒了~~~已经打好草稿了好几篇博客就是懒得总结发布。。。最近经常遇到水平居中和垂直居中的问题,所以就总结了下。

水平居中

1. text-align: center ;
可使用场景 块级元素包含行内元素
 h,p等块级标签,让标签内文本居中
 div块级元素让内部的行内元素居中
2. margin: 0 auto;
块级元素内的块级元素居中
3. position 定位
position: fixed / absoluted;
 left: 50%;
 margin-left: -width/2;
 //块级元素内包含块级元素(宽度已知)
4. transform 属性
margin-left: 50%;//(父元素的百分之50)
 transform: translate(-50%,0); //(自身宽度的50%);
 //块级元素包含块级元素
5. flex 布局
display: flex;
 justify-content: center;

垂直居中

1. line-height 属性
height: 20px;
 line-height: 20px;
 // height = line-height
 // 块级元素内为行内元素
2. display: table;
display: table; //父元素
 display: table-cell; // 子元素
 vertical-align: center;
3. position:定位
position: relative; //父元素
 position: absolute; // 子元素
 top: 50%;
 left: 50%;
 width: 10px;
 height: 20px;
4. flex 布局
display: flex;// 父元素
 align-items: center;
5. transform 属性
margin-top: 50%;//(父元素的百分之50)
 transform: translate(0,-50%); //(自身高度的50%);

Home

Written by Mary Ma, and build some interesting tools .