3

Why is the property name different for:

$(elem).css('padding-top')

and

$(elem).css('marginTop')

? Shouldn't it be:

$(elem).css('margin-top')

instead?

2
  • 1
    "For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on." see - api.jquery.com/css Commented Oct 7, 2012 at 18:11
  • Sorry didn't notice. Got it. :) Commented Oct 7, 2012 at 18:15

2 Answers 2

4

You can use the "camelCase" or "hyphen-separated" form of properties. Both will work. See the jQuery docs for .css():

jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').

So to use your examples, all of the following would work:

$(elem).css('marginTop')
$(elem).css('margin-top')
$(elem).css('paddingTop')
$(elem).css('padding-top')
Sign up to request clarification or add additional context in comments.

4 Comments

The statement quoted here is in the paragraph just above what the OP quotes in his comment.
@BoltClock - Haha, so it is. Perfect demonstration of how it always help to read the docs properly.
Thanks. Must have missed that part :p
sometimes simple things make terrible problem!
1

There are two things. How CSS sees it and how you can access it using JavaScript. In CSS, it is:

#element {margin-top: ...;}

Whereas in JavaScript, it is:

document.getElementById('element').style.marginTop

And yes, both JavaScript way and CSS way of passing to css() function works.

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.