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.target:nth-child(1)").center(true); $("div.target:nth-child(2)").center(false); $(window).resize(function() { $("div.target:nth-child(1)").center(true); $("div.target:nth-child(2)").center(false); });
<div class="container-demo-jquery"> <div class="target">1<br>родитель</div> <div class="target">2<br>окно<br/>браузера</div> </div>
div.container-demo-jquery{ width: 300px; height: 300px; border: 1px solid blue; position: relative; top: 10px; left: 10px; } div.target{ width:100px; height:100px; color:white; background: blue; text-align:center; }