1

I like to write a code that will add margin:0 auto; to a div.

var bestsize = 1445;
 var width = $('.first-image').width();
if( width >= bestsize){
    $('.first-image').css({margin : '0 auto'});

}
else {
    $('.first-image').css({margin :' 0 0 -1px 0'});

}

first-image is a div that has a background image

This is what I have, I think it should work. but maybe i am not stating it correctly. currently nothing will happen. I have feeling that I do not use width the proper way. Can someone give me an idea if this solution is no good?

Thank you very much :)

3
  • i presume that .first-image is a img tag.. if so, are you waiting until the image has loaded before getting the width of it? then you need to check the window.load event Commented Nov 7, 2013 at 19:59
  • what do you mean nothing will happen ? doesn't on of the two css calls execute? Commented Nov 7, 2013 at 19:59
  • The div has a background image, yes the css calls do not execute sorry i am unclear Commented Nov 7, 2013 at 20:03

2 Answers 2

3

why do you need to do it from java-script instead of using CSS media queries?

.first-image{
  margin: 0 0 -1px 0;
}

@media (min-width: 1445px) {
  .first-image{
    margin : 0 auto;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

First can you see anything in your debug console ?

Is jQuery loaded ?

Try this:

You need to wrap it around

$(document).ready(function()({});

to load the function when page is ready

and/or

$(window).resize(function(){});

to load the function on page resize.

Also I would use $('.first-image').css('margin', '0 auto');

2 Comments

hello, thank you for your response. I do have the $(document).ready but i also have other code in there which is why i did not include it here. IF i use this then i do not need if statement? Thank you!
you do but I think the CSS way is probably best

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.