2012-02-21 17 views
8

這個問題隨時會出現在我的腦海中,但由於解決方法非常簡單,我從來沒有費心花時間進一步調查。今天我想我會看到Stack Overflow在這件事上有什麼話要說。使用CSS速記屬性時,保持一定的值不變

比方說,我有這樣的:

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

現在假設我想重寫margin-top#headermargin-bottom。關閉我的頭頂,我通常會做margin: 1em 0;(忘掉前面的規則),但當然這也將覆蓋margin-rightmargin-left。我想要的是一種方法來指定一個速記屬性的某個值不應該改變,這是可能的嗎?這些是我想到的選項:

#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; 
} 
+1

'保證金:1EM inherit'實際上是無效的CSS。您不能在速記屬性中繼承部分值。 – BoltClock 2012-02-21 15:13:21

+0

謝謝!這很有道理,真的。即使堆棧溢出的CSS語法熒光筆似乎知道這一點:)我想你的最後一句話也回答我的問題。 – Simon 2012-02-21 15:16:52

回答

2

這不是現在可能的,不幸的是。你必須堅持分別分配margin-topmargin-bottom

速記屬性總是會更改其組成(longhand)屬性的值全部。即,在一個速記屬性省略的任何值將默認爲initial它們各自的特性,除非由cascading或通過取決於簡寫屬性一些其它規則解決。例如,在汽車的利潤率由於該速記後出現的margin-bottom手寫以下結果上底部以外的所有方面:

#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; 
} 

如果有用於水平邊距和垂直邊距獨立速記,你就可以做到這一點,而不必擔心保持特定的longhand值,但目前沒有這樣的shorthands存在。

正如我在我的評論中提到,margin: 1em inherit是爲CSS-廣泛的關鍵字inherit(與initial一起和其他人在後來的標準中引入)無效只能由自己財產申報出現,這包括速記聲明。即使margin: 1em inherit做工作,該元素將父元素繼承水平的利潤率,而不是從自己的級聯(因爲這不是繼承的含義)。這是不可能給定的元素檢索的屬性級聯或指定的值,並能做到這一點幾乎可以肯定會是容易出錯,由於這樣的事實,從包含解析值最具體的選擇最下面的聲明可以在任何地方

+2

我還是停下來不知道是否像'無change'在WWW風格的郵件列表有人建議......這聽起來比笨重'currentXYZ'關鍵字的主機更好。 – BoltClock 2012-02-21 15:27:18