方法一:display:flex;布局
.sider{
width: 600px;
height: 300px;
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
}
.center{
width: 200px;
height: 200px;
border: 2px solid green;
}
方法二:position与margin结合; (margin:将子元素向左向上分别移动自身宽高的一半)
.sider{
width: 600px;
height: 300px;
border: 2px solid #333;
position: relative;
}
.center{
width: 200px;
height: 200px;
border: 2px solid green;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
方法三:margin 与 transform的translate属性结合 ;translate值分别是在X轴与Y轴方向的偏移量,即为子元素自身宽高的一半
.sider{
width: 600px;
height: 300px;
border: 2px solid #333;
position: relative;
}
.center{
width: 200px;
height: 200px;
border: 2px solid green;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-100px,-100px);
}
方法四:position与margin结合使用
.sider{
width: 600px;
height: 300px;
border: 2px solid #333;
position: relative;
}
.center{
width: 200px;
height: 200px;
border: 2px solid green;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}