总结一下常用的居中方式,主要记录常用的上下左右居中方式和个别上下居中方式及兼容性
对于固定宽高元素
固定宽高 + 设置负margin值(相较于不定宽的transform: translate(-50%))
*需要固定定位 fixed 或者 absolute
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="box">
<div class="content"></div>
</div>
</body>
<style type="text/css">
.box {
width: 500px;
height: 300px;
position: fixed;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -150px;
border: 1px solid red;
}
.content {
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
border: 1px solid blue;
}
</style>
</html>
效果图:
固定宽高 + 绝对定位
*尝试去掉 left + right || top + bottom试试
*固定定位 absolute fixed ,如果没有固定定位,有效果吗
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="box">
<div class="content">我是需要居中的盒子中的内容</div>
</div>
</body>
<style type="text/css">
.box {
width: 500px;
height: 300px;
position: fixed;
right: 0;
left: 0;
margin: auto;
border: 1px solid red;
}
.content {
width: 200px;
height: 100px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
border: 1px solid blue;
}
</style>
</html>
效果图:
对于不定宽高元素
transform: translate(-50%, -50%) 居中元素可以不用设定宽高
*需要固定定位 fixed 或者 absolute
Internet Explorer 10、Firefox、Opera 支持 transform 属性。
Internet Explorer 9 支持替代的 -ms-transform 属性(仅适用于 2D 转换)。
Safari 和 Chrome 支持替代的 -webkit-transform 属性(3D 和 2D 转换)。
Opera 只支持 2D 转换。
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="box">
<div class="content"></div>
</div>
</body>
<style type="text/css">
.box {
width: 500px;
height: 300px;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border: 1px solid red;
}
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border: 1px solid blue;
}
</style>
</html>
效果图:
display: flex;
justify-content: center;
align-items: center;
*在父元素上设置以上布局即可
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="box">
我也居中了
<div class="content">我是需要居中的内容</div>
</div>
</body>
<style type="text/css">
.box {
width: 500px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid red;
}
.content {
border: 1px solid blue;
}
</style>
</html>
效果图:
table-cell + vertical-align
*vertical-align 作用于内联元素以及 display: table-cell 的元素,浮动和绝对定位会让元素块状化,所以在浮动和绝对定位中使用 vertical-align 是不起作用的
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="box">
我也居中了
<div class="content">我是需要居中的内容</div>
</div>
</body>
<style type="text/css">
.box {
width: 500px;
height: 300px;
display: table-cell;
vertical-align: middle;
text-align: center;
border: 1px solid red;
}
.content {
border: 1px solid blue;
}
</style>
</html>
效果图: