用CSS实现水平垂直居中
发布时间:2020-12-14 23:51:43 所属栏目:资源 来源:网络整理
导读:对于CSS的垂直水平居中 ,知道有那么几个,也没有完全的去了解下,现在用些时间来总结下,所有可用的方法。 一、利用margin加position body div class="box"/div/body style type='text/css'*{margin:0px;padding:0px;}div.box { width: 100px; height: 100p
对于CSS的垂直水平居中 ,知道有那么几个,也没有完全的去了解下,现在用些时间来总结下,所有可用的方法。 一、利用margin加position<body> <div class="box"></div> </body> <style type='text/css'> *{margin:0px;padding:0px;} div.box { width: 100px; height: 100px; margin: auto; background-color: red; position: absolute; top: 0; left: 0; right: 0; bottom: 0; } </style> 效果图在这就不放上来啦,就是水平垂直居中的一个div。该方法兼容主流的浏览器,支持到IE8+。 二、负marign加position<body> <div class="box"></div> </body> <style type='text/css'> *{margin:0px;padding:0px;} div.box { position: absolute; width: 100px; height: 100px; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; background-color: red; } </style> 其中magin的负值是居中元素(本身)的宽高的一半。该方法有良好的兼容性,兼容所有浏览器。 三、table-cell<body> <div class="wrap"> <div class="box"></div> </div> </body> <style type='text/css'> *{margin:0px;padding:0px;} div.wrap { display: table-cell; height: 600px; width: 1000px; border: 1px solid #ccc; vertical-align: middle; text-align: center; } div.box { width: 100px; height: 100px; background-color: red; vertical-align: middle; display: inline-block; } </style> 该方法支持IE8+。 四、flex;align-items:center<body> <div class="wrap"> <div class="box"></div> </div> </body> <style type='text/css'> *{margin:0px;padding:0px;} div.wrap { display: flex; align-items: center; justify-content: center; height: 600px; } div.box { width: 100px; height: 100px; background-color: red; } </style> 由于用到了flex,所以,只支持IE10+的主流浏览器。当然在移动端布局时,该方法可以是很不错的选择。 五、display:flex;margin:auto<body> <div class="wrap"> <div class="box"></div> </div> </body> <style type='text/css'> *{margin:0px;padding:0px;} div.wrap { display: flex; height: 600px; } div.box { width: 100px; height: 100px; background-color: red; margin: auto; } </style> 与前一种方法一样,在移动端布局时,可以优先采纳,同样兼容IE10+。 六、transform加position<body> <div class="wrap"> <div class="box"></div> </div> </body> <style type='text/css'> *{margin:0px;padding:0px;} div.wrap { position: relative; height: 600px; } div.box { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); -webkit-transform: translate(-50%,-50%); width: 100px; height: 100px; background-color: red; } </style> 由于用到transform属性,所以该方法仅兼容IE9+的主流浏览器。 先放这几个比较常见的方法吧,以后有更好地方法可以继续添加。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |