让元素垂直居中的几种方法

下面介绍四中让元素居中的方法:

  • 1.定位+margin
    说明:top: 0; left: 0; right: 0; bottom: 0; :这四个属性的设置使得元素在父容器中尝试同时相对于其四个边缘对齐。由于子元素的尺寸固定,这将导致元素无法同时触及所有边界,因此这种设置在没有其他定位信息时不会改变元素位置。
    margin: auto; :这是使元素居中的关键。当元素绝对定位且topbottomleftright都设置为0时,将margin设置为auto会使浏览器自动计算上下和左右的margin,以使元素居中。
css 复制代码
 *{
      padding: 0;
      margin: 0;
    }
    .father{
      width: 400px;
      height: 400px;
      border: 1px solid;
      position: relative;
    }
    .son{
      position: absolute;
      width: 200px;
      height: 200px;
      background-color: pink;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
   
 <div class="father">
    <div class="son"></div>
 </div>
  • 2.定位+transform
    说明: top: 50%; left: 50%; :将元素的顶部和左侧边缘分别定位到其父容器的50%位置。这是相对于父容器的上边缘和左边缘的百分比定位。
    transform: translate(-50%, -50%); :通过使用 translate 转换,元素会向左和向上移动自身宽度和高度的一半 ,实现了水平和垂直方向上的居中效果。这是因为 translate(-50%, -50%) 操作的百分比是相对于元素自身的宽度和高度计算的。
css 复制代码
    .father{
      width: 500px;
      height: 500px;
      border: 1px solid;
      position: relative;
    }
    .son{
      position: absolute;
      width: 200px;
      height: 200px;
      background-color: pink;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
    
   <div class="father">
    <div class="son"></div>
  </div>
  • 3.flex布局
    说明: display: flex; :将父元素设置为 Flexbox 容器,使其内部子元素能够利用 Flexbox 布局。
    justify-content: center; :水平方向上居中对齐子元素。这会使子元素在父容器内水平居中。
    align-items: center; :垂直方向上居中对齐子元素。这会使子元素在父容器内垂直居中。
css 复制代码
    .father{
      width: 500px;
      height: 500px;
      border: 1px solid;
      display: flex; 
      justify-content: center;
      align-items: center;
    }
    .son{
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    
   <div class="father">
    <div class="son"></div>
  </div>
  • 4.grid布局
    说明:display: grid; :将容器设置为Grid布局。
    place-items: center; :这是一个快捷方式,相当于同时设置了 align-items: center;justify-items: center;,使内容在水平和垂直方向上居中。
css 复制代码
    .father{
      width: 500px;
      height: 500px;
      border: 1px solid;
      display: grid;
      place-items: center;
    }
    .son{
      width: 200px;
      height: 200px;
      background-color: pink;
    }
    
    <div class="father">
        <div class="son"></div>
    </div>
相关推荐
海底火旺17 分钟前
JavaScript中的Object方法完全指南:从基础到高级应用
前端·javascript·面试
海底火旺18 分钟前
JavaScript中的Symbol:解锁对象属性的新维度
前端·javascript·面试
天天扭码18 分钟前
一文吃透 ES6新特性——解构语法
前端·javascript·面试
Kagerou20 分钟前
组件测试
前端
JustHappy22 分钟前
啥是Hooks?为啥要用Hooks?Hooks该怎么用?像是Vue中的什么?React Hooks的使用姿势(上)
前端·vue.js·react.js
张可36 分钟前
历时两年半开发,Fread 项目现在决定开源,基于 Kotlin Multiplatform 和 Compose Multiplatform 实现
android·前端·kotlin
嘻嘻嘻嘻嘻嘻ys1 小时前
《Spring Boot 3 + GraalVM原生镜像实战:云原生时代的毫秒启动与性能调优》
前端·后端
嘻嘻嘻嘻嘻嘻ys1 小时前
《Spring Boot 3.0×GraalVM:云原生时代的毫秒级启动实战革命》
前端·后端
嘻嘻嘻嘻嘻嘻ys1 小时前
《Vue 3.4响应式内核优化与WebAssembly性能突破实战指南》
前端·后端
嘻嘻嘻嘻嘻嘻ys1 小时前
《Spring Boot 3百万并发实战:基于JDK21虚拟线程的性能革新》
前端·后端