css的水平垂直居中

css水平垂直居中

文本的水平垂直居中:

<div class="text">center</div>

文本的水平居中:

text-align:center;

文本的垂直居中:

  • 无hight

padding:10px;
  • 有hight

    line-height:height;

line-height–文本的行高

  1. normal

  2. inherit

  3. percent(百分比) —line-height = font-size(父元素的) * 150%

  4. px(像素值)

  5. 纯数字(1.5) –line-height = font-size(自身的) * 1.5

.text{
    display:table-cell;
    vertical-align:middle;
}

盒子的水平垂直居中:

<div class="wrap"><div class="item"></div></div>
  • position + margin

.wrap{position:relative;}
.item{
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin:auto;
}
或者
.item{
    position:absolute;
    top:50%;
    left:50%;
    margin-top: -(height/2);
    margin-left: -(height/2);
}
或者{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}
  • table

.wrap{
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}
.item{
    display:inline-block;
}
  • flex

.wrap{
    display:flex;
    justify-content:center;
    align-items:center;
}
或者
.wrap{
    display:flex;
}
.item{margin:auto;}
    原文作者:starxiao
    原文地址: https://segmentfault.com/a/1190000008004630
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞