水平垂直居中的四种方式

简介: 水平垂直居中的四种方式

html 布局结构如下

<div class="outerBox">
    <div class="innerBox"></div>
</div>

第一种 使用flex

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    display: flex;
    justify-content: center;
    align-items: center;
}
.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;
}

第二种 position + margin:auto

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    position: relative;
}
.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

第三种 position + margin负边距

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    position: relative;
}
.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
}

第四种 transform: translate

.outerBox {
    height: 400px;
    background-color: rgb(12, 243, 232);
    position: relative;
}
.innerBox {
    width: 200px;
    height: 200px;
    background-color: pink;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

遇见问题,这是你成长的机会,如果你能够解决,这就是收获。

相关文章
|
8天前
|
前端开发
CSS水平居中与垂直居中的方法
CSS水平居中与垂直居中的方法
|
8天前
div盒子垂直居中的3种方法
div盒子垂直居中的3种方法
32 2
|
8天前
|
前端开发
css flex布局两个元素水平居中垂直居中
css flex布局两个元素水平居中垂直居中
19 1
|
9月前
|
前端开发
前端水平垂直居中实现
前端水平垂直居中实现
|
8天前
|
前端开发 容器
css中元素水平居中的方式
css中元素水平居中的方式
50 0
div盒子水平垂直居中以及表格的居中的方法
div盒子水平垂直居中以及表格的居中的方法
119 0
|
前端开发
CSS高度塌陷问题及清除浮动的三种方式
在父元素最后增加一个空的块级子元素,并且让它设置clear: both
119 0
|
前端开发 容器
CSS布局的三种方式
CSS布局的三种方式:1.绝对定位 2.相对定位 3.浮动
97 0
CSS布局的三种方式
|
前端开发
CSS的三种布局机制 浮动 清除浮动
CSS的三种布局机制 浮动 清除浮动
161 0
CSS的三种布局机制 浮动 清除浮动

热门文章

最新文章