Maysam
Maysam

Reputation: 7367

JQuery width() does not return correct value

I have a div that has not a preset width in css, I'm trying to center in on screen with JQuery, it works in Chrome, Firefox and IE8+, but does not work in IE7. Why?

css:

.productBoxWrapper{
    height:210px;
    clear:both;
    background-color:blue;
}

JQuery:

$('#mydiv').css("position", "absolute");
this.css("left", ($(window).width() - $("#mydiv").width()) / 2 + "px");

JSFiddle: http://jsfiddle.net/tygcz/3/

Upvotes: 0

Views: 386

Answers (1)

Glorious Kale
Glorious Kale

Reputation: 1313

Try to center it like this:

Css:

#myDiv{
     position: absolute; top: 50%; left: 50%;
}

Script:

$('#myDiv').css('marginLeft', - ( parseInt( $('#myDiv').width() ) / 2) + 'px' );
$('#myDiv').css('marginTop', - ( parseInt( $('#myDiv').height() ) / 2) + 'px' );

I'm not sure weather parseInt is really needed.

Upvotes: 1

Related Questions