先明确几个东西,这几个东西很多初学者可能不太清楚absolute: 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 'left', 'top', 'right' 以及 'bottom' 属性进行规定。fixed: 生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 'left', 'top', 'right' 以及 'bottom' 属性进行规定。relative: 生成相对定位的元素,相对于其正常位置进行定位。static: 默认值。没有定位inherit: 继承自父元素的position属性的值
根据以上解释,相对于父元素#box,我们需要用absolute,以下方法皆是如此
方法1:#box { width: 300px; height: 300px; background: #ddd; position: relative; }#child { width: 150px; height: 100px; background: orange; position: absolute; top: 50%; margin: -50px 0 0 0; line-height: 100px; }
方法2:#box { width: 300px; height: 300px; background: #ddd; position: relative; }#child { background: #93BC49; position: absolute; top: 50%; transform: translate(0, -50%); }
对于文本的居中
最简单的一种方法:vertical-align: middle;