1.利用flex布局
.parent{
width: 100%;
height: 500px;
background-color: aqua;
display: flex;
justify-content: center;
align-items: center;
}
.parent .child{
width: 500px;
height: 300px;
background-color: red;
}
复制代码
以下几个方法都为根据绝对定位来实现
2.可以设置margin值为当前子元素的一半的负值
.parent{
position:relative;
background-color: aqua;
width: 800px;
height: 500px;
}
.parent .child{
width: 500px;
height: 300px;
position: absolute;
background-color: red;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -250px;
}
复制代码
3.把div的top left right bottom 都设置0
.parent{
position: relative;
background-color: aqua;
width: 800px;
height: 500px;
}
.parent .child{
width: 500px;
height: 300px;
position: absolute;
background-color: red;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
复制代码
4.子元素的宽高未知可以利用transfrom属性
.parent{
position: relative;
background-color: aqua;
width: 800px;
height: 500px;
}
.parent .child{
position: absolute;
background-color: red;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END