Leaving certain values ​​unchanged when using CSS verbatim properties

This question appears in my mind from time to time, but since the workaround is so simple that I never worried about taking the time to explore it further. Today it seemed to me that I would see what Qaru can say about this.

Let's say I have this:

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

Now suppose I would like to override margin-top and margin-bottom of #header . At the top of my head, I usually did margin: 1em 0; (forgetting the previous rule), but this, of course, will override margin-right and margin-left . I would like to indicate that a certain value of a shorthand property should not change at all, is this possible? Here are the options I thought 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; } 
+8
css
source share
1 answer

This is currently not possible, unfortunately. You will have to stick with the appropriate margin-top and margin-bottom respectively.

A shorthand property always changes the values ​​of all its components (longhand). Namely, any values ​​omitted in the abbreviated property will be initial by default for their respective properties, unless cascading or other rules are allowed depending on the shorthand property. For example, the following results in an automatic field on all sides except the bottom due to margin-bottom longhand, which appears after the reduction:

 #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 abbreviations for horizontal fields and vertical fields, you could do this without worrying about saving certain lengths, but such abbreviations do not exist at the moment.

As I mentioned in my comment, margin: 1em inherit not valid because CSS inherit (along with initial and others presented in later standards) can only be displayed by themselves in property declarations, and this includes declining declarations. Even if margin: 1em inherit really worked, the element would inherit horizontal fields from its parent element, and not from its own cascade (since this is not what inheritance means). It is impossible to get a cascading or set value for a property for a given element, and the ability to do so will almost certainly be error prone because the lowest declaration from the most specific selector containing the allowed value can be anywhere.

+2
source share

All Articles