just want to center the blue box directly in the center of the screen using jquery.
jsFiddle: http://jsfiddle.net/Pxjkk/
<html>
just want to center the blue box directly in the center of the screen using jquery.
jsFiddle: http://jsfiddle.net/Pxjkk/
<html>
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:
Basics of centering elements in css:
body level (to center in the middle of the screen)position: relative on the containerposition: absolute on the elementwidth and height to the elementtop: 50% and left: 50% on elementmargin-left and margin-top to negative half the width and height respectivelyThe same logic applies for jQuery, only that you can calculate dimensions and margins dynamically.