3

From: Pro PHP and jQuery:

■ Tip The values returned are CSS shorthand properties.3 An added bonus of jQuery is the ability to set CSS properties using CSS shorthand, which doesn't work using basic JavaScript.

From jQuery API Reference:

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

I'm confused, css shorthand can be set, but not read? Of course I'll simply use a stylesheet, but, the question is for academic edification.

1
  • That's right. Even though you might set properties using CSS shorthand, the browser still breaks these out into their respective parts (this is the computed style). Elements don't have a 'margin' property in the browser, they will have 'margin-top', 'margin-right', 'margin-bottom', 'margin-left'. Commented Feb 3, 2012 at 22:01

3 Answers 3

6

You can set shorthand CSS properties, as they are applied and interpreted into the inidividual styles.

However, the reverse process can't be done, unless specifically programmed.

For example, you could program the reader to detect a shorthand property like margin and return the concatenated margin-top, margin-right, margin-bottom and margin-left.

That said, there are several possibilities for the shorthand. For example, margin: 10px 20px still sets all four margins, but retrieving it might yield 10px 20px 10px 20px, which is not the same as was input.

Basically, long story short, shorthand properties translate into exactly one set of individual properties, but one set of individual properties may result in the several possible shorthands.

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

Comments

5

The jquery css shorthands does not work when getting them using the getter method .css(propertyName) method.

You can definetely set css rules with a css shorthand:

$('div').css("border", "2px solid Black");

DEMO

Comments

3

Open up the console if you are on firefox or chrome. Type this:

jQuery(".post-text"); // will select the post of this answer, you should see it in the console
jQuery(".post-text").css("margin"); // will be "", the shorthand returns NOTHING
jQuery(".post-text").css("margin-top"); // will be "0px", the real notation works
jQuery(".post-text").css("margin","10px 10px 10px 10px"); // we just set all margins with shorthand, you should notice a change in the UI of stackoverflow.
jQuery(".post-text").css("margin-top"); // is "10px" now
jQuery(".post-text").css("margin"); // is still ""

I hope this clarifies the concept. Short answer: You can set, but not get shorthand css proprieties.

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.