CSS——实现盒子在页面居中

1.三种常见方法

  1. 使用translate位移 + position定位实现
  2. 使用Grid布局实现
  3. 使用Flex布局实现

2.代码示例

2.1 translate + position:使用绝对定位,让盒子脱离文档流,通过top和left将盒子的左上角放到中心点上,然后使用translate移动使其居中。

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>页面水平垂直居中</title>
    <style>
      .box {
        position: absolute;
        width: 400px;
        height: 400px;
        top: 50%; /* 把元素的"上边缘"放到包含块高度的 50% 处 */
        left: 50%; /*  把元素的"左边缘"放到包含块宽度的 50% 处 */
        transform: translate(-50%, -50%);/*向左、向上各移动自身宽/高的 50%,让元素中心与包含块中心重合 */
        background-color: pink;
    }
    </style>
  </head>
  <body>
    <div class="box">
    </div>
  </body>
</html>

2.2 Grid布局:使用place-item:center实现居中。

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>页面水平垂直居中</title>
    <style>
    .parent {
        display: grid;
        place-items: center; /* 同时水平和垂直居中 */
        height: 100vh;       /* 为了示例效果,父元素设置全屏高度 */
    }
    .child {
        width: 100px;
        height: 100px;
        background-color: blue;
    }
   </style>
  </head>
  <body>
<div class="parent">
   <div class="child"></div>
</div>
  </body>
</html>

2.3 Flex布局:使用justify-content: center和align-items: center,通过控制主轴和交叉轴实现居中。

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>页面水平垂直居中</title>
    <style>
     .parent {
        display: flex;
        justify-content: center; /* 水平居中 */
        align-items: center;    /* 垂直居中 */
        height: 100vh;          /* 为了示例效果,父元素设置全屏高度 */
    }
    .child {
        width: 100px;
        height: 100px;
        background-color: red;
    }
   </style>
  </head>
  <body>
<div class="parent">
   <div class="child"></div>
</div>
  </body>
</html>
相关推荐
开发者小天2 小时前
uniapp中封装底部跳转方法
前端·javascript·uni-app
阿波罗尼亚3 小时前
复杂查询:直接查询/子查询/视图/CTE
java·前端·数据库
正义的大古3 小时前
OpenLayers地图交互 -- 章节九:拖拽框交互详解
前端·vue.js·openlayers
三十_A3 小时前
【实录】使用 Verdaccio 从零搭建私有 npm 仓库(含完整步骤及避坑指南)
前端·npm·node.js
huangql5203 小时前
从零到一打造前端内存监控 SDK,并发布到 npm ——基于 TypeScript + Vite + ECharts的解决方案
前端·typescript·echarts
weixin_456904273 小时前
离线下载npm包
前端·npm·node.js
低代码布道师3 小时前
少儿舞蹈小程序(19)地址列表功能实现及默认地址逻辑
前端·低代码·小程序
90后的晨仔3 小时前
Vue3 + TypeScript + Pinia 实战全解析
前端
90后的晨仔4 小时前
Vue 3 + TypeScript + Pinia 实战架构指南
前端