场景一:物体A相对于整个屏幕水平垂直居中(弹出框)
注:黑色边框是屏幕的尺寸
方法一: 将外边距设置为容器自身宽高的一半
top 和 left 均设置为 50%,然后设置容器外边距 margin 的负间距
(即:margin-top 为容器自身高度一半的负值,margin-left 为容器自身宽度一半的负值)
<body>
<div class="content">
</div>
</body>
<style>
.content {
position: absolute;
width: 500px;
height: 200px;
left: 50%;
top: 50%;
margin: -100px 0 0 -250px; /* 将外边距设置为容器自身的一半 */
background-color: red;
}
</style>
方法二:使用 `transform` 属性
top 和 left 均设置为 50%,然后使用 `transform` 属性
<body>
<div class="content"></div>
</body>
<style>
.content{
position: absolute;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%); /* 使用 `transform`属性 */
background-color: pink;
}
</style>
方法三:设置外边距为 auto
top 、left 、bottom 、right 均设置为 0 ,然后设置外边距 margin 为 auto
<body>
<div class="content"></div>
</body>
<style>
.content{
position: absolute;
width: 200px;
height: 100px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto; /* 设置外边距为 auto */
background-color: blue;
}
</style>
场景二:物体 B 相对于物体 A 水平垂直居中(大div套小div)
注:黑色框表示屏幕,B是相对于A垂直居中
方法一:使用 flex 布局
将 display 值设为 flex,垂直居中 align-items: center; 水平居中 justify-content: center;
<body>
<div class="container">
<div></div>
</div>
</body>
<style>
.container {
width: 300px;
height: 300px;
background-color: red;
display: flex; /* display 值为 flex */
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
.container div {
width: 100px;
height: 100px;
background-color: green;
}
</style>
方法二:给父元素 div 添加宽高,然后设置父元素的 position 为 relative;子元素参考场景一的三种写法
以【场景一】中的【方法一】为例:
<body>
<div class="container">
<div class="content">
</div>
</div>
</body>
<style>
.container{
width:600px;
height:600px;
position: relative; /* 将父元素 position 设置为 relative */
background: yellow;
}
.container .content {
position: absolute;
width: 500px;
height: 200px;
left: 50%;
top: 50%;
margin: -100px 0 0 -250px; /* 将子元素外边距设置为容器自身的一半 */
background-color: red;
}
</style>