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>

结果显示:


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

相关推荐
lyj16899711 分钟前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
小白变怪兽2 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头2 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
墨菲安全3 小时前
NPM组件 betsson 等窃取主机敏感信息
前端·npm·node.js·软件供应链安全·主机信息窃取·npm组件投毒
GISer_Jing3 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆3 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding4 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js
前端开发与ui设计的老司机4 小时前
UI前端与数字孪生结合实践探索:智慧物流的货物追踪与配送优化
前端·ui
全能打工人4 小时前
前端查询条件加密传输方案(SM2加解密)
前端·sm2前端加密
翻滚吧键盘5 小时前
vue绑定一个返回对象的计算属性
前端·javascript·vue.js