几种常见的居中方式

2017-08-18  本文已影响0人  宝林design

1,text-align: center

适用于文字和图片的水平居中,只需要在文字或者 图片的父元素添加text-align: center;即可;

2,margin:0 auto;

适用于确定一个块级元素的宽度后,添加margin:0 auto;j即可;

3,line-height

这是最简单的一种使文字垂直居中的方法,使用line-height属性,但是line-height值要和height的值相同比如:


4, padding

这个只需要设置padding的上下边距相等就可以,比如:padding:20px 0;这种适用于一行只有一块内容,如果有很多块就不推荐使用;

5,vertical-align

这个方法适用于图片和文字居中的情况;如:


6,使用position:absolute

这种方法浏览器基本能兼容,但是就是要先设定宽高,如:

.text{
  position:absolute;
  with:200px;
  height:200px;
  top:50%;
  left:50%;
  margin-left:-100px;
  margin-top:-100px;
  background-color:red;
}

7,transform:translate(x,y)

这个是css3的新属性,在移动端用的比较多,可以不用固定宽高:

.eight{ 
    position:absolute; 
    width:150px; 
    height:150px; 
    top:50%; 
    left:50%; 
    transform:translate(-50%,-50%);
   -webkit-transform:translate(-50%,-50%); 
    -moz-transform:translate(-50%,-50%);
     -ms-transform:translate(-50%,-50%); 
    background:green; 
}

8,table-cell

实现垂直居中时,需要其父元素和子元素同时设置vertical-align: middle;水平居中直接text-align:center,如:

.box{
  width: 400px;
  height: 200px;
  border: 1px solid ;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

9,display: flex

这是弹性布局的居中方法,不废话上代码:

 *{
    margin: 0;
    padding: 0;
}
body{
   background-color: red;
  }
 .text{
   width: 80%;
   margin: 0 auto;
   height: 500px;
   background-color: #fff;
   display: flex;
   align-items: center;
   justify-content: center;
}

上一篇下一篇

猜你喜欢

热点阅读