水平居中
方法一:给div设置宽度后将margin的上下设为0,左右设为auto
<div class="box"></div>
body{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 200px;
background-color: aqua;
margin: 0 auto;
}
效果:
方法二:使小盒子变为行内块从而在大盒子中使用text-aglin属性
<div class="container">
<div class="box"></div>
</div>
body{
margin: 0;
padding: 0;
}
.container{
text-align: center;
background: rgba(0,0,0,0.2);
}
.box{
width: 300px;
height: 200px;
background-color: aqua;
display: inline-block;
}
水平垂直居中
方法一:
<div class="box"></div>
body{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 200px;
margin:auto;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
background-color: salmon;
}
方法二:
<div class="box"></div>
body{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 200px;
margin:-100px -150px;/*为宽高的一半*/
position: absolute;
top:50%;
left:50%;
background-color:palevioletred;
}
方法三:
body{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 200px;
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
background-color:plum;
}
方法四:
body{
margin: 0;
padding: 0;
}
.container{
display: flex;
align-items:center; /*垂直居中*/
justify-content: center; /*水平居中*/
height: 600px;
background-color: chocolate;
}
.box{
width: 300px;
height: 200px;
background-color:seagreen;
}
方法五:
<div class="container">
<div class="box"></div>
</div>
body{
margin: 0;
padding: 0;
}
.container{
position: fixed;
top: 0;
right: 0;
left: 0;
bottom: 0;
background-color: slategray;
text-align: center;
overflow: auto;
white-space:nowrap;
font-size: 0;
}
.container::after{
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.box{
width: 300px;
height: 200px;
display: inline-block;
vertical-align: middle;
background-color:yellow;
white-space: normal;
}