
jQuery如何将div设置为水平垂直居中:
使用CSS也可以实现div的水平垂直居中效果,但是有时候可能需要动态的调整,下面就介绍一下如何用jQuery实现对象的水平垂直居中效果,先看一段代码实例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css">
.mytest{
width:200px
height:100px
background-color:green
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).resize(function(){
$(".mytest").css({
position:'absolute',
left:($(window).width() - $(".mytest").outerWidth())/2,
top:($(window).height() - $(".mytest").outerHeight())/2 + $(document).scrollTop()
})
})
$(window).resize()
})
</script>
</head>
<body>
<div class="mytest"></div>
</body>
</html>
以上代码实现了将div在窗口中水平垂直居中效果,无论是否调整窗口大小。可能有些朋友会说,这个是在窗口中垂直居中的,如何实现一个div在一个普通的福对象中垂直居中,代码修改如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css">
.parent{
width:500px
height:500px
background-color:red
}
.children{
width:200px
height:100px
background-color:green
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).resize(function(){
$(".children").css({
position:'absolute',
left:($(".parent").width() - $(".children").outerWidth())/2,
top:($(".parent").height() - $(".children").outerHeight())/2 + $(document).scrollTop()
})
})
$(window).resize()
})
</script>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
</html>
以上代码实现了字div在父div中的水平垂直居中效果。
<!DOCTYPE html><html>
<body>
<div style="background:redpadding-left:10pxmargin-left:20pxheight:100pxtext-align:centerline-height:100px">
<img src="/images/divcss5.jpg" style="vertical-align:middle" />
</div>
</body>
</html>
// 图片居中的例子 可以参考
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)