[Solved] Center an element directly in the center of screen. jQuery [closed]


To center your blue box, it’s position has to be set to position:absolute;

if your blue box changes size dynamically, you have to center it using javascript.

Here is a quick example:

$('#color')
    .css('top','50%')
    .css('left','50%')
    .css('margin-left','-'+($('#color').outerWidth()/2)+'px')
    .css('margin-top','-'+($('#color').outerHeight()/2)+'px');

Make sure it stays center on browser resize:

$(document).bind('resize', function(){
        $('#color')
        .css('top','50%')
        .css('left','50%')
        .css('margin-left','-'+($('#color').outerWidth()/2)+'px')
        .css('margin-top','-'+($('#color').outerHeight()/2)+'px');
    });

It will probably be a good idea to wrap the centering code into a function and call it whenever the size of the blue box changes.

Here is the edited jsFiddle:

http://jsfiddle.net/mdkpS/

solved Center an element directly in the center of screen. jQuery [closed]