1.flex
该方法时兼容手机端居中的首选
<html>
<head>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid red;
display: flex;
/* 设置弹性布局的方向 */
flex-direction: row;
/* 表示在主轴上对齐居中 */
justify-content: center;
/* 在侧轴上对齐居中 */
align-items: center;
}
.box>div{
width: 100px;
height: 100px;
background: red;
}
</style>
<script>
</script>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
2.flex+margin
<html>
<head>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid red;
/* */
display: flex;
}
.box>div{
width: 100px;
height: 100px;
background: red;
/* 把margin设为自动,可以理解为子元素被四周的 margin “挤” 到了中间*/
margin: auto;
}
</style>
<script>
</script>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
3、absolute+transform
这个方法一般用于图片的居中
<html>
<head>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid red;
/* */
position: relative;
}
.box>div{
width: 100px;
height: 100px;
background: red;
/* 设置绝对定位 */
position: absolute;
/* 把div定位到中间 */
left: 50%;
top: 50%;
/* 由于定位的位置为该div的左上角,从而要往左往上分别移动width/2和height/2 */
transform: translate(-50px, -50px);
}
</style>
<script>
</script>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
4、absolute + 四个方向的值相等
<html>
<head>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid red;
/* */
position: relative;
}
.box>div{
width: 100px;
height: 100px;
background: red;
/* 设置绝对定位 */
position: absolute;
/* margain设为自动 */
margin: auto;
/* 所有值都设为相同即可 */
left: 0;
right: 0;
bottom: 0;
top: 0;
}
</style>
<script>
</script>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
5、grid 网格布局
<html>
<head>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid red;
/* 设为网格布局 */
display: grid;
}
.box>div{
width: 100px;
height: 100px;
background: red;
/* 将 网格项中的内容 对齐到 网格区域 的垂直中间位置 */
align-self: center;
/* 将 网格项中的内容 对齐到 网格区域 的水平中间位置 */
justify-self: center;
}
</style>
<script>
</script>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
但它在兼容性上不如 flex,特别是 IE 浏览器,只支持 IE10 及以上。
6、margin+transform
<html>
<head>
<style>
.box{
width: 500px;
height: 500px;
border: 1px solid red;
}
.box>div{
width: 100px;
height: 100px;
background: red;
/* 把div定位到中间 */
margin-left:50%;
margin-top:50%;
/* 由于定位的位置为该div的左上角,从而要往左往上分别移动width/2和height/2 */
transform: translate(-50px, -50px);
}
</style>
<script>
</script>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>