赞
踩
自从做前端之后,每天面对的都是对齐、居中这些字眼,每次还原设计稿的时候,也都是想起来什么就用什么,没有一个清晰的思路。为了更好的学习,现在将css常见的七中垂直居中布局方案梳理一下,同样这也是面试常被问到的知识点哦。
先放一张效果图,这是用7种不同的方法实现的垂直居中。
接着放实现这张效果图的全部代码。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>css垂直居中常用对齐方案</title> <style type="text/css"> *{padding: 0;margin: 0;} .div1, .div2, .div3, .div4,.div5,.div6,.div7{width: 400px;} .div1{height: 100px;background-color: red;} .div1 p{color: #fff;line-height: 100px;} .div2{height: 100px;background-color: orange;} .div2 p{position: relative;top: 40%;} .div3{height: 100px;background-color: yellow;position: relative;} .div3 p{position: absolute;top: 50%;margin-top: -10.5px;} .div4{height: 100px;background-color: green;position: relative;} .div4 p{position: absolute;top: 0;left: 0;bottom: 0;right: 0;margin: auto 0;height: 21px;} .div5{height: 100px;background-color: blue;display: table-cell;vertical-align: middle;} .div5 p{color: #fff;} .div6{height: 100px;background-color: cyan;display: flex;} .div6 p{color: #fff;margin:auto 0;} .div7{height: 100px;background-color: violet;display: flex;align-items: center; } .div7 p{color: #fff;} </style> </head> <body> <!-- 第一种:使用line-height实现垂直居中 --> <div class="div1"> <p>1、我垂直居中啦。</p> </div> <!-- 第二种:relative相对定位居中 --> <div class="div2"> <p>2、我垂直居中啦。</p> </div> <!-- 第三种:absolute绝对定位居中 --> <div class="div3"> <p>3、我垂直居中啦。</p> </div> <!-- 第四种:absolute+margin实现垂直居中 --> <div class="div4"> <p>4、我垂直居中啦。</p> </div> <!-- 第五种:table-cell实现垂直居中 --> <div class="div5"> <p>5、我垂直居中啦。</p> </div> <!-- 第六种:flex实现垂直居中(一) --> <div class="div6"> <p>6、我垂直居中啦。</p> </div> <!-- 第七种:flex实现垂直居中(二) --> <div class="div7"> <p>7、我垂直居中啦。</p> </div> </body> </html>
代码很简单很简单,看懂的就不需要往下看了,不懂的跟我来。
第一种,line-height居中,这个适合文本使用,并且行高要和容器高度一样
第二种,相对定位居中,top: 40%
,居中为什么是40%而不是50%?你一定会有这个疑问对不对?答案是因为相对定位是根据元素的头去定位的,而不是中间,所以少去的10%是元素自身的高度。
使用这种方式布局的计算是这样的:(容器高度-元素自身高度)/2
第三种,其实和相对定位布局差不多,不同得是这次的top: 50%
,这次不是50%是因为采用了负值的margin来解决定位差距,margin-top: -10.5px;
自身高度的一半。同理,相对布局也可以使用负值的margin来解决定位差距。最后注意使用绝对布局要先设置父元素相对定位属性position: relative
哦。
第四种,利用绝对定位top: 0;left: 0;bottom: 0;right: 0;
这样元素就会充满整个容器,这时候使用margin: auto 0;
就能使元素居中啦。这个记得给元素设定高度哦。
第五种,table-cell这个没什么好解释的,就两句代码display: table-cell;vertical-align: middle;
第六种,flex居中,这个更简单了,也是两句代码,父元素设置display: flex;
子元素直接使用margin:auto 0;
就能实现居中了。
第七种,还是flex弹性布局,不过这个使用的不是margin,而是flex自带的垂直居中属性align-items: center;
当然css实现垂直居中的方法还有很多很多。这里只是从宏观上去梳理了几种常见并且好用的,特别是最后的flex弹性布局非常好用,不过对比与其他方法有那么一点小门槛,后续会单独把flex弹性布局拿出来说。
有问题的朋友的欢迎留言评论,可能秒回哦。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。