方法一:使用 flex布局 1
HTML 结构如下:父元素 outer 子元素 inner
<div class="outer">
<div class="inner"></div>
</div>
css 样式:
父元素设置为 flex布局 加入以下代码,实现子元素自动居中
display: flex;
justify-content: center;
align-items: center;
完整 css 代码如下:
.outer{
height: 400px;
width: 400px;
background-color: #888;
display: flex;
/* 方案一:设置水平、垂直居中 */
justify-content: center;
align-items: center;
}
.inner{
height: 100px;
width: 100px;
background-color: orange;
}
效果展示:橙色盒子(子元素) 自动在父元素居中对齐
方法二:使用 flex布局 2
还是上面的结构,但是父元素的下面这两行代码去掉:
justify-content: center;
align-items: center;
去掉后在子元素加入
margin: auto;
完整 css 代码
.outer{
height: 400px;
width: 400px;
background-color: #888;
display: flex;
}
.inner{
height: 100px;
width: 100px;
background-color: orange;
/* 方案二: 父元素设置flex布局 子元素 */
margin: auto;
}
方法三:使用 grid 布局
父元素设置 grid 布局,设置水平垂直居中
display: grid;
place-items: center;
完整 css 代码
.outer{
height: 400px;
width: 400px;
background-color: #888;
/* 设置grid布局 */
display: grid;
place-items: center;
}
.inner{
height: 100px;
width: 100px;
background-color: orange;
}
方法四:一些大总结
1.水平居中:
如果子元素为块级元素 如 div 父元素设置以下代码可以水平居中
margin: 0 auto;
对于内联元素(如 <span>
或 <a>
)或行内块元素,需要水平居中可以使用
text-align: center;
2.垂直居中:
若子元素为块元素,给子元素加上
margin-top: (父元素高-子元素总高) / 2
若子元素为行内元素、行内块元素 需要设置行高为子元素的高度
line-height = height;
/*注意height为子元素的总高*/
每个子元素加上
vertical-align: middle;
若想要绝对垂直居中则在父元素加上,同时这行代码还可以消除 HTML 结构换行带来的空格,但注意子元素的字体大小需要重新设置
font-size: 0px;
方法五:借助定位 1
子元素设置 绝对定位
.inner{
/* 块级元素包含块级元素,可以使用定位水平、垂直居中 */
height: 100px;
width: 400px;
background-color: orange;
font-size: 20px;
position: absolute;
/* 方案一 更推荐*/
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
父元素设置 相对定位
.outer{
height: 400px;
width: 800px;
background-color: #ccc;
position: relative;
}
方法六:借助定位 2
子元素设置定位,然后手动计算需要移动的距离
margin-top:-元素高度/2 px;
margin-left:-元素宽度/2 px;
.inner{
/* 块级元素包含块级元素,可以使用定位水平、垂直居中 */
height: 100px;
width: 400px;
background-color: orange;
font-size: 20px;
position: absolute;
/* 方案二 */
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -200px;
}
方法七:借助定位 + 2D变换---移动
这种方式比方法五好一些,不需要计算具体要移动多少像素
transform: translate(-50%,-50%);
完整 css 代码如下:
.inner{
/* 块级元素包含块级元素,可以使用定位水平、垂直居中 */
height: 100px;
width: 400px;
background-color: orange;
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
/* 方案三 */
transform: translate(-50%,-50%);
}