jquery实现div上下左右居中显示

时间:2026-02-15 17:26:49

1、新建html文档。

jquery实现div上下左右居中显示

2、书写hmtl代码。

<div class="outer"> 

<div class="inner">

<div class="inner"></div>

</div>

</div> 

jquery实现div上下左右居中显示

3、书写css代码。

<style type="text/css">

body{padding:0; margin:0;background:#eee;}

.outer,.inner{border:2px solid #999;}

.outer{ width:70%;height:80%;}

.inner{ width:50%; height:80%; }

p.info{ position:absolute;top:10px;right:10px;background:#EB3755;color:#fff;font-family:arial,sans-serif;font-size:15px;margin:0;padding:20px;z-index:2;}

</style>

jquery实现div上下左右居中显示

4、书写并添加js代码。

<script src="js/jquery.min.js"></script>

<script>

    (function($){

        $(document).ready(function(){

$.fn.center=function(){

return this.each(function(){

var $this=$(this),

parent=$this.parent(),

topPos,

topMargin,

leftMargin,

resizeTimeout;

if(parent.is("body:not(.root-height-set)")){

$("html,body").css("height","100%").addClass("root-height-set");

}

if($this.css("position")==="absolute" || $this.css("position")==="fixed"){

topPos="50%";

topMargin="-"+Math.round($this.outerHeight()/2)+"px";

leftMargin="-"+Math.round($this.outerWidth()/2)+"px";

$this.css({"left":"50%","margin-left":leftMargin});

}else{

topPos=Math.floor((parent.height()-$this.outerHeight())/2);

topMargin="auto";

$this.css({"position":"relative","margin-left":"auto","margin-right":"auto"});

}

$this.css({"top":topPos,"margin-top":topMargin});

$(window).resize(function(){

if(resizeTimeout){

clearTimeout(resizeTimeout);

}

resizeTimeout=setTimeout(function(){

if($this.css("position")==="absolute"){

topMargin="-"+Math.round($this.outerHeight()/2)+"px";

leftMargin="-"+Math.round($this.outerWidth()/2)+"px";

$this.css({"margin-left":leftMargin,"margin-top":topMargin});

}else{

topPos=Math.floor((parent.height()-$this.outerHeight())/2);

$this.css("top",topPos);

}

},150);

});

});

}

$(".outer,.inner").center();

        });

    })(jQuery);

</script>

jquery实现div上下左右居中显示

5、代码整体结构。

jquery实现div上下左右居中显示

6、查看效果。

jquery实现div上下左右居中显示

© 2026 一点资料
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com