Horizontally centered
Method 1: After setting the width of the div, set the upper and lower margins to 0, and the left and right to auto
<div class="box"></div>
body{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 200px;
background-color: aqua;
margin: 0 auto;
}
Effect:
Method 2: Make the small box into an inline block to use the text-aglin attribute in the big box
<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;
}
Center horizontally and vertically
method one:
<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;
}
Method Two:
<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;
}
Method three:
body{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 200px;
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
background-color:plum;
}
Method four:
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;
}
Method Five:
<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;
}