Simon Simon - 1 year ago 57
CSS Question

Leaving certain values unchanged when using CSS shorthand properties

This question pops up in my mind form time to time, but since the workaround is so simple I have never bothered taking the time to investigate it further. Today I thought I'd see what Stack Overflow has to say on the matter.

Let's say I have this:

/* Selector setting up shared properties for some elements */
#header, #main, #footer {
margin: 0 5%;

Now assume I would like to override
. Off the top of my head I usually would do
margin: 1em 0;
(forgetting about the preceding rule), but that will of course also override
. What I would like is a way to specify that a certain value of a shorthand property should not change at all, is that possible? These are the options I have come to think of:

#header {
margin: 1em 0; /* Will remove left/right margin */
margin: 1em auto; /* Will revert to default left/right margin */
margin: 1em inherit; /* Will inherit left/right margin from parent */
margin: 1em no-change; /* This is what I'm after: shorthand property to set only 2 of 4 values */

/* And this is how I end up solving it */
margin-top: 1em;
margin-bottom: 1em;

Answer Source

This isn't currently possible, unfortunately. You'll have to stick with assigning margin-top and margin-bottom respectively.

A shorthand property always changes the values of all its component (longhand) properties. Namely, any values omitted in a shorthand property will default to initial for their respective properties unless resolved by cascading or by some other rules depending on the shorthand property. For example, the following results in auto margins on all sides except the bottom due to the margin-bottom longhand that appears after the shorthand:

#header {
     * Note: this is short for margin: auto auto auto auto;
     * none of the longhands are set to initial! Different shorthands
     * have different rules, but a shorthand always changes the values
     * of all its longhands.
    margin: auto;
    margin-bottom: 1em;

If there were separate shorthands for horizontal margins and vertical margins, you would be able to do this without having to worry about keeping specific longhand values, but no such shorthands exist at the moment.

As I mentioned in my comment, margin: 1em inherit is invalid as the CSS-wide keywords inherit (along with initial and others introduced in later standards) may only appear by themselves in property declarations, and this includes shorthand declarations. Even if margin: 1em inherit did work, the element would inherit horizontal margins from its parent element, and not from its own cascade (since that's not what inheritance means). It is not possible to retrieve a cascaded or specified value for a property on a given element, and being able to do this would almost certainly be error-prone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download