<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS绝对居中</title>
<!--
CSS绝对居中解决方案
一、定宽高:
1.绝对定位+负margin值
2.绝对定位+margin auto
二、不定宽高:
1.绝对定位+transform
2.table-cell
3.flex -->
<style>
.box-wrapper{
width: 300px;
height: 300px;
border: 1px solid #000;
position: relative;
}
/* 第一种:定宽高-绝对定位+负margin值 */
.box-absolute-margin{
width: 200px;
height: 200px;
background-color: mediumblue;
/* 关键因素 */
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px; /*margin-left/top负值根据width和height来决定,取值为一半;*/
margin-top: -100px;
}
/* 第二种:定宽高-绝对定位+margin auto */
.box-absolute-margin-auto{
width: 200px;
height: 200px;
background-color: mediumblue;
/* 关键因素 */
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
/* 第三种:不定宽高-绝对定位+transform */
.box-absolute-transform{
background-color: yellow;
/* 关键因素 */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /*向x,y移动: 移动距离为自身盒子宽高的50%*/
}
/* 第四种:不定宽高-table-cell */
.box-wrapper-table-cell{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box-table-cell{
background-color: yellowgreen;
display: inline-block;
}
/* 第五种:不定宽高-flex */
.box-wrapper-flex{
display: flex;
justify-content: center;
align-items: center;
}
.box-flex{
background-color: tomato;
}
</style>
</head>
<body>
<!-- 第一种:定宽高-绝对定位+负margin值 -->
<div class="box-wrapper">
<div class="box-absolute-margin"></div>
</div>
<br>
<!-- 第二种:定宽高-绝对定位+margin auto -->
<div class="box-wrapper">
<div class="box-absolute-margin-auto"></div>
</div>
<br>
<!-- 第三种:不定宽高-绝对定位+transform -->
<div class="box-wrapper">
<div class="box-absolute-transform">
的撒的吾问无为谓无若多
</div>
</div>
<br>
<!-- 第四种:不定宽高-table-cell -->
<div class="box-wrapper box-wrapper-table-cell">
<div class="box-table-cell">
少时诵诗书所大付错
</div>
</div>
<br>
<!-- 第五种:不定宽高-flex -->
<div class="box-wrapper box-wrapper-flex">
<div class="box-flex">
flex的点点滴滴多多多多多多多
</div>
</div>
<br>
</body>
</html>