相信很多初学者朋友在学习Java前端页面的时候很困惑一个问题,如何实现一个元素在父元素中上下居中并且左右呢?
笔者上网查了一下,发现要么网上答案答非所问,要么就是很片面,仅仅实现了上下居中或者仅仅实现左右居中。
所以,特地抽了一点时间来做一个Demo,同时实现上下居中、左右居中。
<body>
<div id="foo" style="width: 200px; height: 200px; background: #ccc;">
<div id="s" style="width: 50px; height: 20px; background: #ccc;">1111</div>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.center = function(obj) {
this.css("position", "absolute");
this.css("top", ($(obj).height() - this.height()) / 2
+ $(obj).scrollTop() + "px");
this.css("left", ($(obj).width() - this.width()) / 2
+ $(obj).scrollLeft() + "px");
return this;
}
//Use the above function as:
$('#foo').center(window);
$('#s').center('#foo');
</script>
说明一下,这里实现的是id为foo的<div>在整个界面上下左右居中(父元素),id为s的<div>在id为foo的父元素<div>中实现上下左右居中。
结果如下: