3

Need to center an object whose width changes depending on the browser window. Usually I'd use css with top and left positions set to 50% with a negative margin equal to half the width and height, but obviously that wouldn't accomodate this need.

I thought my jQuery function would work... but no bueno. am i missing something in CSS?

Thanks!

http://jsfiddle.net/danielredwood/EbkLg/2/

Here's the CSS

#t {
        width:25%;
        height:25%; 
        background:red;
    }

JavaScript

$(window).resize(function(){
     resizenow();
});
function resizenow() {
    var browserwidth = $(window).width();
    var browserheight = $(window).height();
    $('#t').css('left', (browserwidth - $(this).width())/2).css('top', (browserheight - $(this).height())/2);
});
13
  • Is your code something that's getting called on the windows resize() event? Or are you just trying to statically set the position of the object once using javascript?
    – kinakuta
    Jun 17, 2011 at 0:08
  • 1
    @kinakuta: Your answer deserves the checkmark for being more complete than mine. However, I do not think the OP understands that the width(), height(), css() and calculations are all being performed with the pixel values (unit-less) and not percent.
    – Sparky
    Jun 17, 2011 at 1:01
  • 1
    I get that part. I thought at first you were saying width() returned the value as having "px" on it, as if it had to be parsed out. I see re-reading your comment that's not what you said. Regardless, I understand how width works - my comment was in the context of the original post which styled the object with static pixel values.
    – kinakuta
    Jun 17, 2011 at 1:03
  • 1
    @kinakuta: I see. Yes you do, and I did not realize that css() would default to using 'px' when no units are specified. However, when I started adding 'px' within the css() in the original fiddle, I was able to get it working for some reason. And the OP's comment on my answer below was so baffling, it sent me up here to make these quick comments. ;)
    – Sparky
    Jun 17, 2011 at 1:11
  • 1
    Yeah, I think a lot of confusion was injected when it was changed from the original 500px width and height values to the 25% values which I didn't even notice until long after.
    – kinakuta
    Jun 17, 2011 at 1:13

6 Answers 6

2

In your JSFiddle that you linked to you use $(this).width():

$('#t').css('left', ((browserwidth - $(this).width())/2))
.css('top', ((browserheight - $(this).height())/2));

But when the function resizenow() is called, this == window. If you replace $(this) with $("#t") it works fine, as this JSFiddle shows: http://jsfiddle.net/jackfranklin/F2tR3/1/

Within the css() function of jQuery, the value of this is not set to the element whose style(s) you are changing, hence why your original code didn't work.

1
  • This is why my version worked and I didn't even realize it at first - +1
    – kinakuta
    Jun 17, 2011 at 1:17
2

Something like this?

 $(document).ready(function(){  

var browserwidth = $(window).width();
var browserheight = $(window).height();
var x=browserwidth/4;
$('#t').css({'left': (browserwidth - x)/2 + 'px', 'top': (browserheight - x)/2  + 'px'});

$(window).resize(function(){

  var browserwidth = $(window).width();
  var x=browserwidth/4;
  var browserheight = $(window).height();

   $('#t').css({'width' : x, 'height' : x,  'left': (browserwidth - x)/2 + 'px', 'top': (browserheight - x)/2  + 'px'});
   });


#t {
width: 500px;
height: 500px;
position: relative;
    background:red;
 }


               });

Or if you don't want it to be a square, just don't set width and height in jquery, use percentage in css.

1

It's the way value is getting parsed for the left and top values you're trying to set. If you break them out like this, it works:

var widthDelta = $(window).width() - $('#t').width();
var heightDelta = $(window).height() - $('#t').height();
$('#t').css('left', widthDelta / 2).css('top', heightDelta / 2);

I haven't analyzed exactly what was going wrong - I just looked for something that worked first - I'll have to look at it closer to see what the problem specifically was.

1
1

jQuery width() and height() returns a unit-less pixel value according to the jQuery documentation.

But when you plug it back into a calculation for jQuery's css(), you need to add the units label "px".


EDIT:

If your calculation is based on percentages, then everything is wrong since width() and height() are pixel values. Either way, you still need to add units, either 'px' or '%' within jQuery's css().


EDIT2:

css() apparently defaults to using pixels but if the OP is using percentages, then '%' would be required.

2
  • Nothing's dealing with pixels.. css can handle percents. Jun 17, 2011 at 0:26
  • @technopeasant: You need to read the jQuery documentation. See this.
    – Sparky
    Jun 17, 2011 at 0:29
0

This will horizontally center the red div, and it's width and height will dinamically change according to the browser windows size;

<div style="position:absolute;display:block;left:0;right:0;top:0;bottom:0;">
<div style="width:25%;height:25%;background:red;display:block;margin:auto;"></div>
</div>

Now the vertical centering is a bit more complex story...

-1

Try adding position:fixed to your CSS. This will mean that any positioning that you specify for the element will be in regards to the actual window instead of the document.

Not sure if this will fix it but it should.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.