Leaving certain values unchanged when using CSS shorthand properties

前端 未结 1 996
感情败类
感情败类 2020-12-11 02:23

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

相关标签:
1条回答
  • 2020-12-11 03:13

    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 due to the fact that the bottommost declaration from the most specific selector that contains the resolved value could be anywhere.

    0 讨论(0)
提交回复
热议问题