css 样式
<body>
<div id="box">
<div id="box1"></div>
</div>
</body>
方法一:flex 布局
#box {
height: 400px;
height: 400px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
#box1 {
width: 200px;
height: 200px;
background-color: pink;
}
方法二: 绝对定位加 margin
#box {
position: relative;
height: 400px;
width: 400px;
border: 1px solid red;
}
#box1 {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: pink;
}
方法三:绝对定位加负 margin
#box {
position: relative;
height: 400px;
width: 400px;
border: 1px solid red;
}
#box1 {
position: absolute;
height: 200px;
width: 200px;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
background-color: pink;
}
方法四:绝对定位加 transform
#box {
width: 400px;
height: 400px;
position: relative;
border: 1px solid red;
}
#box1 {
position: absolute;
height: 200px;
width: 200px;
background-color: pink;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法五:grid 布局
#box {
width: 400px;
height: 400px;
display: grid;
<!-- display: flex; -->
border: 1px solid red;
}
#box1 {
width: 200px;
height: 200px;
margin: auto;
background-color: pink;
}
方法六:利用定位加 css3 的计算属性
#box {
width: 400px;
height: 400px;
border: 1px solid red;
position: relative;
}
#box1 {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: calc(50% - 100px);
left: calc(50% - 100px);
}