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>

结果显示:


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

相关推荐
snow@li4 分钟前
前端:前端/浏览器 可以录屏吗 / 实践 / 录制 Microsoft Edge 标签页、应用窗口、整个屏幕
前端·浏览器录屏·前端录屏·web录屏
李贺梖梖10 分钟前
CSS学习
前端·css
蚂小蚁19 分钟前
一文吃透:宏任务、微任务、事件循环、浏览器渲染、Vue 批处理与 Node 差异(含性能优化)
前端·面试·架构
狼性书生31 分钟前
uniapp实现的Tab 选项卡组件模板
前端·uni-app·vue·组件·插件
吃饺子不吃馅36 分钟前
前端画布类型编辑器项目,历史记录技术方案调研
前端·架构·github
拜晨1 小时前
使用motion实现小宇宙贴纸墙效果
前端·交互设计
拜晨1 小时前
使用motion实现小宇宙节目广场的效果
前端·交互设计
知花实央l1 小时前
【Web应用实战】 文件上传漏洞实战:Low/Medium/High三级绕过(一句话木马拿webshell全流程)
前端·学习·网络安全·安全架构
华仔啊1 小时前
JavaScript + Web Audio API 打造炫酷音乐可视化效果,让你的网页跟随音乐跳起来
前端·javascript