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>

结果显示:


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

相关推荐
IT瘾君21 分钟前
JavaWeb:Html&Css
前端·html
264玫瑰资源库1 小时前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏
喝拿铁写前端1 小时前
从圣经Babel到现代编译器:没开玩笑,普通程序员也能写出自己的编译器!
前端·架构·前端框架
HED1 小时前
VUE项目发版后用户访问的仍然是旧页面?原因和解决方案都在这啦!
前端·vue.js
拉不动的猪1 小时前
前端自做埋点,我们应该要注意的几个问题
前端·javascript·面试
王景程2 小时前
如何测试短信接口
java·服务器·前端
安冬的码畜日常2 小时前
【AI 加持下的 Python 编程实战 2_10】DIY 拓展:从扫雷小游戏开发再探问题分解与 AI 代码调试能力(中)
开发语言·前端·人工智能·ai·扫雷游戏·ai辅助编程·辅助编程
小杨升级打怪中2 小时前
前端面经-JS篇(三)--事件、性能优化、防抖与节流
前端·javascript·xss
清风细雨_林木木2 小时前
Vue开发网站会有“#”原因是前端路由使用了 Hash 模式
前端·vue.js·哈希算法
鸿蒙布道师3 小时前
OpenAI为何觊觎Chrome?AI时代浏览器争夺战背后的深层逻辑
前端·人工智能·chrome·深度学习·opencv·自然语言处理·chatgpt