HTML+CSS 元素水平垂直居中<6种>
文章目录
首先初始化一个盒子
<body>
<div class="box"></div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
html,body {
width: 100%;
height: 100%;
}
.box {
width: 200px;
height: 200px;
background-color: aquamarine;
}
</style>
第1种方法:绝对定位(absolute)和margin:auto实现
<body>
<div class="box pos-1"></div>
</body>
/* 另添加pos-1类 */
/*绝对定位(absolute)和margin:auto实现 */
.pos-1 {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
第2种方法:绝对定位(absolute)和回退自身宽高一半
<body>
<div class="box pos-2"></div>
</body>
/* 另添加pos-2类 */
/* 2.绝对定位(absolute)和回退自身宽高一半 */
.pos-2 {
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
第3种方法:绝对定位(absolute)和transform
<body>
<div class="box pos-3"></div>
</body>
/* 另添加pos-3类 */
/* 3.绝对定位(absolute)和transform */
.pos-3 {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
第4种方法:flex布局 justify-content和align-items
<body>
<div class="box pos-4"></div>
</body>
/* 另添加pos-4类 */
/* 4.flex布局 justify-content和align-items */
html,body {
width: 100%;
height: 100%;
/* 另添加属性 */
display: flex;
justify-content: center;
align-items: center;
}
.pos-4 {
不用写,不用另添加类,修改其 父类(body)
}
第5种:文本水平垂直居中text-align+line-height
<body>
<div class="box pos-5">这是一首简单的小情歌</div>
</body>
/* 另添加pos-5类 */
/* 5.文本垂直居中 */
.pos-5 {
text-align: center;
line-height: 200px; //设定值与其自身height一样
}
第6种:盒子不设宽高,inline-block+padding
<body>
<div class="box pos-6">这是一首简单的小情歌</div>
</body>
/* 另添加pos-6类 */
/* 6.文本垂直居中 */
.box {
/* width: 200px;
height: 200px; */
background-color: aquamarine;
/*新增属性*/
display: inline-block;
}
.pos-6 {
padding: 20px;
}