0

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);
0

3 Answers 3

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Err, isn't $img a collection of DOM elements? What are the values of $width and $height?
I'm making a slideshow based on certain specs. There are different image sizes and its meant to to pull the image height and width from the image.
1

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%');

2 Comments

'-$height/2' is still a string and an invalid margin-top value.
$('#boxOverlay').css('marginTop', -$height/2);
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.