一、margin方法
(1) 通过内外边距把盒子挤到中间
先用top和left值对子盒子位置进行调整之后,子盒子的左上角的那个顶点是处于父盒子的中心点位置,但是我们要让子盒子垂直居中就是要让父盒子和子盒子的中心点在同一位置,因此我们还需要对子盒子向左移动半个宽度的距离,向上移动半个高度的距离,这里采用的是通过调整子盒子外边距来让中心点对齐的方法。
需要注意的是:margin的%的值是以父元素的宽度为基准的,开始在这里我就犯了这个个错误:我写的margin是:
margin:-50% 0 0 -50%;
然后子盒子移到了父盒子外面,并没有如我想象般的中心点重合
因此我们在给margin(上-右-下-左)填数据的时候直接填数字,或者将数字转换成相比父元素宽度的百分比形式。
<div class="parent">
<div class="son"></div>
</div>
.parent{
position: relative;
width: 800px;
height: 500px;
border: 1px solid black;
}
.son{
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin: -100px 0 0 -100px;
background-color: pink;
}
margin:-12.5% 0 0 -12.5%;
(2)通过 margin:auto
我们知道一般盒子使用 margin:auto 只能实现水平居中,垂直居中是不能实现的,因为正常的文档流当中w3c默认规定margin-top和margin-right为0,所以实现不了垂直居中,只有绝对定位的元素才可以。详解参考:margin:auto水平居中和垂直居中的原理分析_世态炎凉!!的博客-CSDN博客_marginauto垂直居中
.parent{
position: relative;
width: 800px;
height: 600px;
border: 1px solid black;
}
.son{
position: absolute;
width: 200px;
height: 200px;
top: 0;
right: 0;
bottom: 0;
left: 0px;
margin: auto;
background-color: pink;
}
二、line-height方法
line-height适合于单行的“行内元素”,所以我们要用line-height首先需要把子盒子.son从块级元素转换成行内元素,代码如下:
.parent{
width: 800px;
height: 600px;
line-height: 600px;
text-align: center;
border: 1px solid black;
}
.son{
display: inline-block;
vertical-align: middle;
width: 200px;
height: 200px;
background-color: pink;
}
!!!尤其注意:要基线对齐!不然子盒子还是不在中心位置
vertical-align: middle;
三、transform方法
CSS3新特性,transform:translate(X,Y),主要掌管元素的变形、旋转和位移。
.parent{
width: 800px;
height: 600px;
border: 1px solid black;
}
.son{
width: 200px;
height: 200px;
transform: translate(300px,200px);
background-color: pink;
}
四、display:flex 弹性布局方法
display:flex 是一种布局方式。它即可以应用于容器中,也可以应用于行内元素。是W3C提出的一种新的方案,可以简便、完整、响应式地实现各种页面布局。
.parent{
display: flex;
justify-content: center;
align-items: center;
width: 800px;
height: 600px;
border: 1px solid black;
}
.son{
width: 200px;
height: 200px;
background-color: pink;
}
justify-content: center; //水平方向居中显示
align-items: center; //垂直方向上居中显示