How Do I Center A Div In The Middle Of The Page Using Jquery And Keep It Centered When Window Is Re-sized?
Does anyone know of any jQuery Script that will keep a div centered in the middle and when the window is re-sized, it will also keep it centered? I am building a lightbox plugin an
Solution 1:
Try that along with the example code you already have. For clarification:
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    returnthis;
}
$(document).ready(function(){
   $('.element').center();
   window.onresize = function(event) {
        $('.element').center();
    }
});
Solution 2:
-----------------This works---------------------
CSS
.box{
    width:200px;
    top:-5px; 
    position:relative;
    background:#444;
}
.inner {
    height:0px;
    width:0px;
    background:#444;
    top:50%;
    left:50%;
    right:50%;
    bottom:50%;
    position:relative;
}
.outer { height:200px; width:400px; border:2px dotted red; }
HTML
<divclass="outer"><divclass="inner"><divclass="box">
        wpfw efuiweh fuiwehf weuifh weuifh fuihwe fuihwefuiweh uwehf iuwehf uiwefhweuifh weuifhwe fuiweh fuiwehfuiwefh uiwefh weuifh weuifh weuifhwe uifh weuifhwefuiweh fuiweh fuiwehf iweufh weuih
    </div></div></div>jQuery
$(function(){
    $(".box").css('top',-($(".box").height()/2));
    $(".box").css('left',-($(".box").width()/2));
});
Please let me know if that doesn't do what you want it to. You can even see on http://jsfiddle.net/mazlix/m4Ttk/2/ that resizing the inner our outer divs will still keep it centered.
Solution 3:
for fixed-size fits example http://jsfiddle.net/expert/vh2vy/5/
Post a Comment for "How Do I Center A Div In The Middle Of The Page Using Jquery And Keep It Centered When Window Is Re-sized?"