flex布局
.box {
width: 500px;
height: 500px;
border: 1px solid red;
margin: 100px auto;
display: flex; /* 核心代码 */
justify-content: center; /* 核心代码 */
align-items: center; /* 核心代码 */
}
.children {
width: 100px;
height: 100px;
background-color: #ccc;
}
position定位
// 第一种写法,用于不知道子元素的宽高
.box {
width: 500px;
height: 500px;
border: 1px solid red;
margin: 100px auto;
position: relative; /* 核心代码 */
}
.children {
width: 100px;
height: 100px;
background-color: #ccc;
position: absolute; /* 核心代码 */
top: 50%; /* 核心代码 */
left: 50%; /* 核心代码 */
transform: translate(-50%,-50%); /* 核心代码 */
}
// 第二种写法,用于知道子元素的宽高
.box {