web前端实现水平垂直居中positionrelativeabsolutetransformtranslateautodisplayflexjustifyaligncenter
Posted web半晨
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了web前端实现水平垂直居中positionrelativeabsolutetransformtranslateautodisplayflexjustifyaligncenter相关的知识,希望对你有一定的参考价值。
目录
1、文本水平垂直居中
HTML
<div class="text_box">
<span>文本实现垂直水平居中</span>
</div>
CSS
.text_box
width: 230px;
height: 60px;
/* 水平居中 */
text-align: center;
/* 垂直居中 */
line-height: 60px;
background-color: #ccc;
2、使用定位实现水平居中/宽高未知
2.1、transform
HTML
<div class="unknown_wh_box">
<div></div>
</div>
CSS
.unknown_wh_box
position: relative;
.unknown_wh_box>div
width: 230px;
height: 230px;
background-color: #ccc;
position: absolute;
left: 50%;
transform: translateX(-50%);
2.2、margin
HTML
<div class="unknown_wh_box">
<div></div>
</div>
CSS
.unknown_wh_box
position: relative;
.unknown_wh_box>div
width: 230px;
height: 230px;
background-color: #ccc;
position: absolute;
left: 0;
right: 0;
margin: auto;
3、使用定位实现水平垂直居中/宽高已知
3.1、transform
HTML
<div class="known_wh_box">
<div></div>
</div>
CSS
.known_wh_box
width: 70%;
height: 300px;
position: relative;
background-color: #aaa;
.known_wh_box>div
width: 230px;
height: 230px;
background-color: #ccc;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
3.2、margin
HTML
<div class="known_wh_box">
<div></div>
</div>
CSS
.known_wh_box
width: 70%;
height: 360px;
position: relative;
background-color: #aaa;
.known_wh_box>div
width: 230px;
height: 230px;
background-color: #ccc;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
4、弹性布局实现水平垂直居中
4.1、未知宽高
高度会自动被撑开,且紧贴子容器。
HTML
<div class="unknown_wh_box">
<div></div>
</div>
CSS
.unknown_wh_box
display: flex;
justify-content: center;
align-items: center;
.unknown_wh_box>div
width: 230px;
height: 230px;
background-color: #ccc;
4.2、已知宽高
HTML
<div class="known_wh_box">
<div></div>
</div>
CSS
.known_wh_box
width: 70%;
height: 360px;
background-color: #aaa;
display: flex;
justify-content: center;
align-items: center;
.known_wh_box>div
width: 230px;
height: 230px;
background-color: #ccc;
以上是关于web前端实现水平垂直居中positionrelativeabsolutetransformtranslateautodisplayflexjustifyaligncenter的主要内容,如果未能解决你的问题,请参考以下文章