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

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

  • 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>
相关推荐
Moment2 分钟前
给大家推荐一个超好用的 Marsview 低代码平台 🤩🤩🤩
前端·javascript·github
小满zs6 分钟前
Zustand 第三章(状态简化)
前端·react.js
普宁彭于晏8 分钟前
元素水平垂直居中的方法
前端·css·笔记·css3
恋猫de小郭19 分钟前
为什么跨平台框架可以适配鸿蒙,它们的技术原理是什么?
android·前端·flutter
云浪23 分钟前
元素变形记:CSS 缩放函数全指南
前端·css
明似水38 分钟前
用 Melos 解决 Flutter Monorepo 的依赖冲突:一个真实案例
前端·javascript·flutter
独立开阀者_FwtCoder1 小时前
stagewise:让AI与代码编辑器无缝连接
前端·javascript·github
清沫1 小时前
Cursor Rules 开发实践指南
前端·ai编程·cursor
江城开朗的豌豆1 小时前
JavaScript篇:对象派 vs 过程派:编程江湖的两种武功心法
前端·javascript·面试
不吃糖葫芦31 小时前
App使用webview套壳引入h5(二)—— app内访问h5,顶部被手机顶部菜单遮挡问题,保留顶部安全距离
前端·webview