Center with variable width using jQuery

You need to center the object, the width of which varies depending on the browser window. Usually I used css with the top and left positions set to 50%, with a negative margin equal to half the width and height, but obviously this would not fit this need.

I thought my jQuery function would work ... but without bueno. Am I missing something in CSS?

Thank!

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

Here is 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);
});
+3
source share
6 answers

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

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

resizenow(), this == window. $(this) $("#t"), , JSFiddle: http://jsfiddle.net/jackfranklin/F2tR3/1/

css() jQuery this , , .

+2

- ?

 $(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;
 }


               });

, , , jquery, css.

+2

jQuery width() height() < jQuery documentation.

jQuery css(), "px".


EDIT:

, , width() height() - . , "px", "%" jQuery css().


EDIT2:

css(), -, , OP , '%'.

+1

, . , :

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

, - -, - , , .

+1

This will horizontally center the red div, and its width and height will dynamically change depending on the size of the browser windows;

<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 vertical centering is a bit more complicated story ...

0
source

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

Not sure if this will fix it, but it should.

-1
source

All Articles