首先需要创建一个容器,容器种添加一个小div,实现小div在容器种的垂直水平居中。
<style>
* {
margin: 0;
padding: 0;
}
.container {
width: 500px;
height: 500px;
background-color: orange;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="content"></div>
</div>
</body>
1.方法一:在已知宽度的情况下,对div改变外边距进行偏移达到效果
代码:
.container {
width: 500px;
height: 500px;
background-color: orange;
position: relative;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
2.方法二:宽度可未知的情况,使用tansform属性达到效果
.container {
width: 500px;
height: 500px;
background-color: orange;
position: relative;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3.方法三:使用弹性布局flex
.container {
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
background-color: orange;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
}
4.方法四:使用table-cell,需要注意的是content块需要给予inline-block
.container {
display: table-cell;
/* 垂直居中 */
vertical-align: middle;
/* 水平居中 */
text-align: center;
width: 500px;
height: 500px;
background-color: orange;
}
.content {
display: inline-block;
width: 100px;
height: 100px;
background-color: red;
}
5.方法五:使用grid布局
.container {
display: grid;
width: 500px;
height: 500px;
background-color: orange;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
justify-self: center;
align-self: center;
}
如有其他方法,后期补充。