CSS水平居中和垂直居中的方法

2018-07-24  本文已影响0人  jackie季

本篇文章主要介绍本人最近在CSS学习中整理总结出的水平&垂直居中的几种方法

水平居中

子元素为行内元素、单个块状及多个块状元素布局方案不同

  1. 行内元素:对父元素设置text-align: center;
  2. 块状元素:子元素设置margin: 0 auto;
  3. 多个块状元素:有三种方式
    a. 子元素全部设置为display: inline-block;,父元素设置text-align: center;
    b. flex布局,父元素display: flex; justify-content: center;
    c. 如果是在多行各自居中,直接给子元素设置margin: 0 auto;

垂直居中

子元素为单行内联、多行内联文本及块状元素布局方案不同

  1. 单行内联文本:父元素高度一定,设置line-height等于height
    父元素高度不定,子元素设置上下```padding``
  2. 多行内联文本:父元素设置display: table-cell; vertical-align: middle;
  3. 块状元素:有五种方式
    a. 使用position:absolute,设置left、top、margin-left、margin-top的属性
.box{
position:absolute;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-100px;
}

b. 使用position:absolute,设置top::0;bottom:0;margin:auto;

c. 使用CSS3的transform属性

.box{
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
}

d. 使用before,after伪元素

.box:before{
    content:'';
    display:inline-block;
    vertical-align:middle;
    height:100%;
}
.content{
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  vertical-align: middle;
}

e. 使用flex布局,父元素display: flex; align-items: center;

上一篇下一篇

猜你喜欢

热点阅读