针对盒子垂直水平居中的解决方案

盒子在窗口垂直水平居中有七种方法:

40dda3ae5afb4f8aaaa4799fc7c1d495.jpg

第一种:利用负的margin来进行居中,需要知道固定宽高,限制比较大。

body>div:nth-of-type(1){ width:400px; height:400px; background:#ff0; position:relative; margin-bottom:10px;}

body>div:nth-of-type(1)div{ width:100px; height:100px; background:#0f0; position:absolute; top:50%; left:50%; margin-left:-50px; margin-top:-50px;}

第二种:利用绝对定位居中,非常常用的一种方法。body>div:nth-of-type(2){ width:400px; height:400px; background:#ff0; position:relative; margin-bottom:10px;}

body>div:nth-of-type(2) div{ width:100px; height:100px; background:#0f0; position:absolute; top:0; left:0; right:0; bottom:0; margin:auto;}

第三种:使用flex布局(.min宽高可不固定)

body>div:nth-of-type(3){ width:400px; height:400px; background:#ff0; margin-bottom:10px; display:flex;}

body>div:nth-of-type(3) div{ width:100px; height:100px; background:#0f0; margin:auto }

第四种:flex居中(演示)。CSS3中引入的新布局方式,比较好用。缺点:IE9以及IE9一下不兼容。

body>div:nth-of-type(4){ width:400px; height:400px; background:#ff0; margin-bottom:10px; display:flex; justify-content:center;align-items:center}

body>div:nth-of-type(4) div{ width:100px; height:100px; background:#0f0; }

第五种:利用table-cell来控制垂直居中。

body>div:nth-of-type(5){ width:400px; height:400px; background:#ff0; margin-bottom:10px; vertical-align:middle; display:table-cell; text-align:center;}

body>div:nth-of-type(5) div{ width:100px; height:100px; background:#0f0; display:inline-block }

第六种:利用空盒子做外容器,里边的块元素会自动垂直居中,只需要控制一下水平居中就可以达到效果。

body>div:nth-of-type(6){ width:400px; height:400px; background:#ff0; margin-bottom:10px; text-align:center;}

body>div:nth-of-type(6) div{ width:100px; height:100px; background:#0f0; display:inline-block; vertical-align:middle }

body>div:nth-of-type(6) span{ width:0; height:100%; display:inline-block; vertical-align:middle;}

第七种:这种方法灵活运用CSS中transform属性,较为新奇。缺点是IE9下不兼容。

body>div:nth-of-type(7){ width:400px; height:400px; background:#ff0; position:relative; margin-bottom:10px;}

body>div:nth-of-type(7) div{ width:100px; height:100px; background:#0f0; position:absolute; top:50%; left:50%; transform:translate(-50%,-50%)}

这七种是我们经常可以遇到的例子,大家可以在今后的工作学习中熟练并且掌握,可以很好的解决现实中遇到的某些实际问题。

来源:千锋HTML5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值