Reputation:
I want to apply a css style using jquery to an element that has a fixed width.
I want to make it´s margin-left be (minus) the width of the element divide by two.
How can I do that?
this is the css:
.top_middle{
width: 33%;
overflow: hidden;
height: 49%;
position: absolute;
}
I tried with something like this but it doesn´t work:
var width = $('.top_middle').width()
$('.top_middle').css(function(){
'margin-left' : - "width" / 2
})
Upvotes: 1
Views: 1159
Reputation: 5768
In your code you are trying to divide the string "width" by 2, which is not what you want. You want to divide the variable width by 2, like this:
$('.top_middle').css({
marginLeft : - (width / 2) + 'px'
});
Also you're passing a function to css(), you should pass an object or a pair of arguments corresponding to a css property and the value you want to set for it.
Upvotes: 1
Reputation: 10260
In your function you have width in "" marks which means it will be run as a string not pick up the variable try
Edit: Your function seems wrong for the jquery syntax try
var width = $('.top_middle').width() / 2;
$('.top_middle').css('margin-left',-width);
See example here http://jsfiddle.net/domjgreen/ydEwx/2/
Upvotes: 1
Reputation: 36531
try this
var halfwidth = $('.top_middle').width()/2;
$('.top_middle').css({'margin-left' : "-" + halfwidth });
Upvotes: 0