如何使用jQuery在屏幕上居中显示div?
要使div在屏幕上居中,请使用jQuery居中功能jQuery.fn.center。您可以尝试运行以下代码,以了解如何在屏幕上居中div:
示例
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
jQuery.fn.center = function(parent) {
if (parent) {
parent = this.parent();
} else {
parent = window;
}
this.css({
"position": "absolute",
"top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
"left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
});
return this;
}
$("div.myclass:nth-child(1)").center(true);
$("div.myclass:nth-child(2)").center(false);
});
</script>
<style>
div.box {
width:300px;
height:300px;
border:2px solid #000000;
position:relative;
top:10px;
left:10px;
}
div.myclass {
width:50px;
height:50px;
color:white;
background: #000000;
border-radius: 4px;
text-align:center;
}
</style>
</head>
<body>
<div class="box">
<div class="myclass">1<br>parent</div>
<div class="myclass">2<br>window</div>
</div>
</body>
</html>热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语