公共样式
.wrapper{
300px;
height: 300px;
background-color: chartreuse;
margin-right: 30px;
display: inline-block;
}
.content{
100px;
height: 100px;
background-color: rgb(30, 210, 195);
font-size: 20px;
line-height: 100px;
text-align: center;
}
1、position定位(细分为3种)
.wrapper1{
position: relative;
}
.content1{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
.wrapper2{
position: relative;
}
.content2{
position: absolute;
margin-left: 50%;
margin-top: 50%;
transform: translate(-50%, -50%);
}
.wrapper3{
position: relative;
}
.content3{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2、行内元素居中
.wrapper4{
text-align: center;
line-height: 300px;
vertical-align: top;
}
.content4{
display: inline-block;
vertical-align: middle;
}
3、弹性盒子布局
.wrapper5{
display: flex;
align-items: center;
justify-content: center;
}
具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.wrapper{
300px;
height: 300px;
background-color: chartreuse;
margin-right: 30px;
display: inline-block;
}
.content{
100px;
height: 100px;
background-color: rgb(30, 210, 195);
font-size: 20px;
line-height: 100px;
text-align: center;
}
.wrapper1{
position: relative;
}
.content1{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
.wrapper2{
position: relative;
}
.content2{
position: absolute;
margin-left: 50%;
margin-top: 50%;
transform: translate(-50%, -50%);
}
.wrapper3{
position: relative;
}
.content3{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.wrapper4{
text-align: center;
line-height: 300px;
vertical-align: top;
}
.content4{
display: inline-block;
vertical-align: middle;
}
.wrapper5{
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<!-- div.wrapper.wrapper$*5>div.content.content${$} -->
<div class="wrapper wrapper1">
<div class="content content1">1</div>
</div>
<div class="wrapper wrapper2">
<div class="content content2">2</div>
</div>
<div class="wrapper wrapper3">
<div class="content content3">3</div>
</div>
<div class="wrapper wrapper4">
<div class="content content4">4</div>
</div>
<div class="wrapper wrapper5">
<div class="content content5">5</div>
</div>
</body>
</html>