-5

just want to center the blue box directly in the center of the screen using jquery.

jsFiddle: http://jsfiddle.net/Pxjkk/

<html>
Josue Espinosa
  • 517
  • 1
  • 4
  • 12

2 Answers2

1

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/

AlexCheuk
  • 4,873
  • 6
  • 28
  • 34
0

Basics of centering elements in css:

  • Make a container for your element and put it at body level (to center in the middle of the screen)
  • Set position: relative on the container
  • Set position: absolute on the element
  • Add fixed width and height to the element
  • Set top: 50% and left: 50% on element
  • Set margin-left and margin-top to negative half the width and height respectively

The same logic applies for jQuery, only that you can calculate dimensions and margins dynamically.

elclanrs
  • 85,039
  • 19
  • 126
  • 159