spriore
spriore

Reputation: 613

Set jQuery .css() based on variable

I'm trying to set the margin-top and margin-left values to half of an element's respective size so as to center it. However it just goes 50% on the left and top.

    var $img = document.getElementsByClassName('box'); 
    var $width = $img.clientWidth;
    var $height = $img.clientHeight;
    $('#overlay').append('<div id="boxOverlay"></div>');
    $('#boxOverlay').css('position', 'fixed');
    $('#boxOverlay').css('top', '50%');
    $('#boxOverlay').css('margin-top', '-$height/2');
    $('#boxOverlay').css('left', '50%');
    $('#boxOverlay').css('margin-left', '-$width/2');
    $('#boxOverlay').css('max-height','80%');
    $('#boxOverlay').css('max-width','90%');
    $('#boxOverlay').height($height);
    $('#boxOverlay').width($width);

Upvotes: 0

Views: 5654

Answers (3)

pdoherty926
pdoherty926

Reputation: 10359

Try this:

var $img = $('.box');
var $width = $img.width();
var $height = $img.height();
// ...
$('#boxOverlay').css('margin-top', (($height / 2) * -1));
$('#boxOverlay').css('margin-left', (($width / 2) * -1));

Fiddle

Also, it's a best practice to pass a style object to the css method:

var styles = {
    'margin-top': (($height / 2) * -1),
    'margin-left': (($width / 2) * -1)
};

$('#boxOverlay').css(styles);

With this approach, you only query the DOM once and you'll avoid multiple repaint and/or reflows (citation needed).

Upvotes: 2

theatlasroom
theatlasroom

Reputation: 1184

Get rid of the single quote marks around the variables you want to use. By adding quote marks around your variables you're actually passing the function [.css()] a string literal instead of a variable.

MDN - Strings

Upvotes: 0

Bieber_zh_cn
Bieber_zh_cn

Reputation: 11

in jquery the margin-left is marginLeft Remove the middle of the dash you can try

$('#boxOverlay').css('marginTop', '-$height/2');
$('#boxOverlay').css('maxHeight','80%');
$('#boxOverlay').css('maxWidth','90%');

Upvotes: 1

Related Questions