1、flex 方式
有效的代码是这三行,这样的话就是在主轴上和交叉轴上都是居中的,实现了水平垂直居中,这种方式应该是几种里面最简单的,而且是弹性布局,不需要知道宽高。不过这个是有兼容性的问题,老版本的IE不要用。
flex布局不知道的话可以看一下菜鸟的那个教程,这是网址,根据它的解释,有什么不懂得点查一下基本就行了。
https://www.runoob.com/w3cnote/flex-grammar.html
display: flex;
justify-content: center;
align-items: center;
<style>
.box{
height: 300px;
width: 500px;
background: deeppink;
display: flex;
justify-content: center;
align-items: center;
}
.box-child{
background: pink;
}
</style>
<div class="box">
<div class="box-child">
luluwang
</div>
</div>
2、定位方式
1、绝对定位,50%减自身宽高
这个方法的好处就是不需要知道具体的宽高,根据比例来算,不能用flex的话用这个也挺好的
<style>
.box {
position: absolute;
}
.box-child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="box">
<div class="box-child">
luluwang
</div>
</div>
2、绝对定位,上下左右全0,margin:auto
这种方法也是利用的定位,虽然没有考虑宽高是多少,但是必须要有宽高
<style>
.box{
position: relative;
}
.box-child{
position: absolute;
height: 100px;
width: 150px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
<div class="box">
<div class="box-child">
luluwang
</div>
</div>