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

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

  • 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>
相关推荐
学问小小谢33 分钟前
第21节课:前端构建工具—自动化与模块化的利器
运维·前端·学习·计算机·自动化·电脑·硬件工程
Orange3015113 小时前
深入剖析Electron的原理
前端·javascript·electron
大模型铲屎官3 小时前
掌握 HTML5 多媒体标签:如何在所有浏览器中顺利嵌入视频与音频
前端·html·音视频·html5·多媒体标签
爱编程的鱼3 小时前
HTML5教程之标签(2)
前端·html·html5
大模型铲屎官4 小时前
告别页面刷新!如何使用AJAX和FormData优化Web表单提交
前端·javascript·ajax·html·编程·页面刷新·表单提交
无限大.7 小时前
前端知识速记--HTML篇:src和href
前端·html
子非鱼9217 小时前
两栏布局、三栏布局、水平垂直居中
前端·javascript·css
程序猿小D8 小时前
第三百五十八节 JavaFX教程 - JavaFX滑块
java·前端·数据库
GISer_Jing9 小时前
React中useState()钩子和函数式组件底层渲染流程详解
前端·react.js·前端框架
私人珍藏库10 小时前
Google Chrome-便携增强版[解压即用]
前端·chrome