CSS垂直居中的方法

作者:流年 | 创建时间: 2023-03-28
这里为大家介绍下CSS垂直居中的办法。要垂直居中先要看已知条件和要居中的是什么东西。...
CSS垂直居中的方法

操作方法

先明确几个东西,这几个东西很多初学者可能不太清楚 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%); }

对于文本的居中 <div id="box">    我是一段测试文本</div> css代码: #box{    width: 300px;    height: 300px;    background: #ddd;    line-height: 300px; }

最简单的一种方法:vertical-align: middle;

点击展开全文

更多推荐