一、行内元素居中

  • 水平居中:设置父元素文本对齐方式为居中(taxt-align: center;)
  • 垂直居中:设置父元素的行高等于容器高度 (line-height: 100%;)
  • 水平垂直居中:水平居中+垂直居中
<style>
.ta-center{
    text-align: center;
}
.lhh-block{
    line-height: 60px;
}
</style>
<div class="lhh-block center">
   <span>行内元素水平垂直居中</span>
</div>

二、块级元素居中

  • 水平居中 :设置左右外边距为自适应(margin: 0 auto)
  • 水平垂直居中(固定高度):绝对定位 + margin负值
<style>
.parent{
    position: relative;
    height: 100px;
    border: 1px solid #333;
}
.block{
    width: 200px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    position: absolute;
    top: 50%;
    right: 50%;
    margin-top: -30px;
    margin-right: -100px;
    border: 1px solid #ccc;
}
</style>
<div class="parent">
   <div class="block">块级元素水平垂直居中</span>
</div>
  • 水平垂直居中(自适应高度):绝对定位+transform
<style>
.parent1{
    position: relative;
    height: 100px;
    border: 1px solid #333;
}
.block1{
    width: 200px;
    height: auto;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid #ccc;
}
</style>
<div class="parent1">
   <div class="block1">块级元素水平垂直居中</span>
</div>

三、Flexible Box弹性布局-简称flex