css使元素垂直水平居中

在搭建网页的时候, 我们往往会让某个元素垂直水平居中来实现自己的布局。本文总结了使元素垂直水平的几种方法,废话不多说直接开始。


使用定位配合transform

给父元素使用相对定位,使子元素在绝对定位时以该父元素为基准。

css 复制代码
.box1{
    position: relative;
    width: 300px;
    height: 300px;
    background-color: skyblue;
}

.box2{
    width: 150px;
    height: 150px;
    background-color: orange;
    /*使用绝对定位*/
    position: absolute;
    top: 50%;
    left: 50%;
    /* 手动计算自身的宽高的一半 */
    /* margin-top: -75px;
    margin-left: -75px; */
    /* 使用平移变化来 自动计算自身的宽高的一半 */
    transform: translate(-50%,-50%);
}

<div class="box1">
    <div class="box2"></div>
</div>

结果显示:


使用定位配合margin

css 复制代码
.box1{
    position: relative;
    width: 300px;
    height: 300px;
    background-color: skyblue;
}

.box2{
    width: 150px;
    height: 150px;
    background-color: orange;
    /* 搭配 margin:auto 使用 */
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

<div class="box1">
    <div class="box2"></div>
</div>

结果显示:


flex布局

css 复制代码
.box1{
    width: 300px;
    height: 300px;
    background-color: skyblue;
    /* 使用弹性布局 */
    display: flex;
    align-items: center;
    justify-content: center;
}

.box2{
    width: 150px;
    height: 150px;
    background-color: orange;
}

<div class="box1">
    <div class="box2"></div>
</div>

结果显示:


以上是一些常见的使元素垂直居中的方法,具体应该根据实际情况选择适合的方法,还有哪些方法呢 欢迎补充。

相关推荐
KaMeidebaby17 分钟前
卡梅德生物技术快报|骆驼纳米抗体:从原核表达、高通量测序到分子对接全流程实现
前端·数据库·其他·百度·新浪微博
子兮曰2 小时前
Node.js v26.1.0 深度解读:FFI、后量子密码与调试器的进化
前端·后端·node.js
测试员周周3 小时前
【Appium 系列】第06节-页面对象实现 — LoginPage 实战
开发语言·前端·人工智能·python·功能测试·appium·测试用例
西洼工作室4 小时前
前端直传OSS服务端签名(Policy+Signature)/STS临时凭证
前端·文件上传·oss
你很易烊千玺4 小时前
日常练习-数组 字符串常用的场景
前端·javascript·字符串·数组
weixin199701080165 小时前
[特殊字符] RESTful API 接口规范详解:构建高效、可扩展的 Web 服务(附 Python 源码)
前端·python·restful
存在的五月雨5 小时前
Vue3项目一些语法
前端·javascript·react.js
nashane6 小时前
HarmonyOS 6学习:Web组件同层渲染事件处理与智能长截图实现
前端·学习·harmonyos·harmonyos 5
大家的林语冰6 小时前
Node 2026 发布,JS 三大新功能上线,最后一个奇偶版本
前端·javascript·node.js