当我们做弹窗的时候,避免不了的就是要做一个上下左右都居中的盒子,公司里面现在内用的方法我觉得并不够简单,适应性也不够强。偶尔有一次看知乎的时候发现一个更简单的方法,并且适应性也更强,个人觉得很好用,这里mark一下,同时也分享给大家。
先来说一下公司里面的用法,直接上代码,这里只贴中间要居中的css了,其他的不多说:
.container{position:absolute;top:50%;left:50%;width: 500px;height: 400px;margin-left: -250px;margin-top: -200px;border:1px solid #000;}
这里的思路其实是得到要居中的宽高,然后绝对定位距左50%,距上50%,然后再向下向右移一半的距离,这样就能把居中的盒子水平垂直居中了。这里就算过了,没什么问题。
我发现的这个代码的思路并不需要知道需要居中的盒子的宽高,直接看代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上下左右都居中</title>
<link rel="stylesheet" href="../../css/base.css">
<style>
body{position: relative;}
/*旧版本的水平垂直居中*/
/*.container{position:absolute;top:50%;left:50%;width: 500px;height: 400px;margin-left: -250px;margin-top: -200px;border:1px solid #000;}*/
/*新版本的水平垂直居中*/
.container{width: 500px;height: 500px;border:1px solid #000000;position: absolute;margin: auto;left: 0;right: 0;top: 0;bottom: 0;}
</style>
</head>
<body>
<div class="container"></div>
<script src="../../js/Common/jquery.js"></script>
<script>
$(function(){
$("body").width($(window).width());
$("body").height($(window).height());
});
</script>
</body>
</html>
其实它的思路很简单,就是让你要居中的盒子上也不是,下也不是,左也不是,右也不是,这样它就能在中间了。很Q的思路,这样做的弹窗就不会都是固定大小的宽高了,完全可以让用户的体验更好