[英]How do you set the CSS styles of child elements from within the parent's style attribute?
例:
<div style="SET IMAGE ATTRIBUTES HERE!">
<img src="http://somesite.com/someimg.jpg"><br />
<img src="http://someothersite.com/someotherimg.jpg"><br />
...
</div>
由於動態ASP.NET代碼生成的結構,我寧願避免使用預定義的CSS類。 這些屬性從一個Web控件到另一個Web控件將有所不同,並且不能在<head>
或<body>
部分中進行全局設置。 例如,我可能在一個頁面上有兩個Web控件,每個Web控件都為其所有子圖像設置了不同的CSS屬性。
作為最后的選擇,我可以為這些控件組合一個動態CSS類生成器-但這將是一個巨大的痛苦,結果確實很草率。 即,每個Web控件將生成自己的CSS類,以某種方式將其寫入head
或body
部分,同時確保多個Web控件的CSS類名稱不相同。 就像我說的那樣,馬虎亂七八糟-因此,我希望能夠將所有這些信息塞入單個控件的屬性標簽中,以免它們踩到彼此的腳趾。
簡短的答案是你不能。
樣式元素的值完全等於具有與該元素匹配的選擇器的規則集(除非具有更高的特異性)。
將屬性值分配給內部元素的唯一方法是,如果該元素具有“ whatever-property-it-is: inherit
”規則whatever-property-it-is: inherit
(在IE的較早版本中是錯誤的)。
你能做這樣的事情:
<div id="yourcontrol_1">
<img src="/some/image.jpg">
</div>
然后在樣式表中定義樣式-不內聯:
#yourcontrol_1 img {
border: 20px double red;
}
這樣,您指定的任何內容僅適用於id為yourcontrol_1
的img
標簽。
內聯樣式IIRC無法實現此控制級別。
如果您無法事先確定類名/標識,您仍然可以生成它們,並使用style
標簽嵌入樣式。 正如您所說:不漂亮,但是可以。
<html>
<head>
<style>
#generated_identifier_0xcafe img {
padding: 200em;
}
#generated_identifier_0xbeef img {
background-color: green;
}
</style>
</head>
<body>
<div id="generated_identifier_0xcafe">
<img src="someimage.png">
</div>
<!-- etc... -->
您不需要類來做您想要的事情,只需將style
屬性放在圖像本身上即可。
<div>
<img src="http://somesite.com/someimg.jpg" style="image styles here!"><br />
<img src="http://someothersite.com/someotherimg.jpg" style="image styles here!"><br />
...
</div>
這是不可能的。 使用內聯CSS,您只能為當前元素設置樣式。
HTML5為樣式標簽引入了一個實驗性scoped
屬性,該屬性將完全滿足您的要求:
<div>
<style scoped>img { border: 20px double red; }</style>
<!-- style applies to this div and its children only -->
它被標記為“尚未准備好生產代碼”,但是在我剛剛做的一個簡單測試中,它就可以在Firefox,Chrome和Edge中使用。 HTML Doctor列出了幾種有效的用例,例如主題插件和Wiki代碼上的用戶定義樣式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.