1.水平居中text-align:center;

在没有浮动的情况下,我们可以让需要居中的块级元素设为inline/inline-block,然后在其父元素上添加text-aline:center;即可。如果想要居中的块级元素是内联元素(span,img,a等),直接在其父元素上添加text-align:center;即可。

.father{
      width: 200px;
      height: 200px;
      background-color: aqua;
      text-align: center;
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: brown;
      display: inline-block;
    }
<div class="father">
    <div class="son"></div>
</div>

2.使用margin:0 auto;水平居中

居中的元素必须是块级元素,如果是行内元素,需要添加display:block;而且元素不浮动。

.father{
      width: 200px;
      height: 200px;
      background-color: aqua;
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: brown;
      margin: 0 auto;
    }
<div class="father">
    <div class="son"></div>
</div>

3.定位实现水平垂直居中(需要计算偏移值)

必须要知道居中的元素的宽高

.father{
    width: 200px;
    height: 200px;
    background-color: aqua;
    position: relative;
}
.son{
    width: 100px;
    height: 100px;
    background-color: brown;
    position: absolute;
    left: 50%; 
    top:50%;
    margin-left: -50px;
    margin-top:-50px;
}
<div class="father">
    <div class="son"></div>
</div>

4.定位实现居中(不需计算偏移值)

margin:auto;和四个方向定位搭配使用,不需要知道元素的宽高

.father{
      width: 200px;
      height: 200px;
      background-color: aqua;
      position: relative;
    }
.son{
    width: 100px;
    height: 100px;
    background-color: brown;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
<div class="father">
    <div class="son"></div>
</div>

5.定位配合css3新属性transform:translate(x,y)使用

不需要知道元素的宽度和高度,在移动端用的比较多,因为移动端对css3新属性的兼容性比较好。

.father{
      width: 200px;
      height: 200px;
      background-color: aqua;
      position: relative;
}
.son{
      width: 100px;
      height: 100px;
      background-color: brown;
      position: absolute;
      top:50%;
      left: 50%;
      transform: translate(-50%,-50%);
}
<div class="father">
    <div class="son"></div>
</div>

6.css3新属性calc()和定位配合使用(需要知道元素的宽高)

用于动态计算长度值。

需要注意的是,运算符前后都需要保留一个空格,例如:width: calc(100% - 10px);

任何长度值都可以使用calc()函数进行计算

calc()函数支持 "+", "-", "*", "/" 运算;

calc()函数使用标准的数学运算优先级规则;

.father{
      width: 200px;
      height: 200px;
      background-color: aqua;
      position: relative;
}
.son{
      width: 100px;
      height: 100px;
      background-color: brown;
      position: absolute;
      left: calc(50% - 50px);
      top: calc(50% - 50px);
}
<div class="father">
    <div class="son"></div>
</div>

7.使用flex弹性盒布局 实现水平垂直居中

不需要知道元素本身的宽高以及元素的属性

.father{
      width: 200px;
      height: 200px;
      background-color: aqua;
      display: flex;
      justify-content:center; 
      align-items:center; 
}
.son{
      width: 100px;
      height: 100px;
      background-color: brown;
}
<div class="father">
    <div class="son"></div>
</div>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐