针对div垂直水平居中的处理方案

作者 : 开心源码 本文共1960个字,预计阅读时间需要5分钟 发布时间: 2022-05-12 共143人阅读

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

第一种:利使用负的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%)}

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

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 针对div垂直水平居中的处理方案

发表回复