<div id="box">
<div id="child">test vertical align</div>
</div>
-
绝对定位+transform
#box { width: 300px; height: 300px; background: #ddd; position: relative; } #child { background: orange; position: absolute; top: 50%; //div顶边距离box的位置 transform: translate(0, -50%);//向y轴反方向(即向上)平移元素高度的一半 }
transform
指变换、变形,是css3
的一个属性,和其他width
,height
属性一样;translate
是transform
的属性值,是指元素进行2D变换,元素以当前位置(0,0)按照x
轴的方向移动多少,按照y
轴的方向移动多少。
-
绝对定位+负外边距
#box { width: 300px; height: 300px; background: #ddd; position: relative; } #child { width: 50%; height: 30%; background: orange; position: absolute; top: 50%; margin: -15% 0 0 0; }
设置child
的高度为box
的30%
(可以是0-100%
任意值x
);使用绝对定位脱离文档流;设置child
上边界距离box
上边界为50%*box高度
;设置child
的上margin
上移15%
(x
的一半)。
-
绝对定位+margin:auto
#box { width: 300px; height: 300px; background: #ddd; position: relative; } #child { width: 200px; height: 100px; background: orange; position: absolute; top: 0; bottom: 0; margin: auto; line-height: 100px; }
将child
元素相对父元素绝对定位;设置bottom
和top
为相等值;设置child
的margin
属性为auto
-
flex布局
#box { width: 300px; height: 300px; background: #ddd; display: flex; align-items: center; } #child { width: 300px; height: 100px; background: orange; }
父元素设置display: flex
为弹性盒子;添加盒子内项目在纵轴上的对齐方式为center
。
-
flex设定纵轴为主轴
#box { width: 300px; height: 300px; background: #ddd; display: flex; flex-direction: column; justify-content: center; } #child { width: 300px; height: 100px; background: orange; }
给父元素设置弹性盒子;改变主轴方向为纵轴flex-direction: column
;justify-content
属性定义项目在主轴上的对齐方式为居中。