簡體   English   中英

我如何避免` <style>` tags getting caught in my CSS selectors?

[英]How do I avoid `<style>` tags getting caught in my CSS selectors?

我正在使用 CSS 來設置一些現有文檔的樣式,並使用許多相鄰的同級選擇器(例如 item1 + item2)在元素之間應用間距等。 但是,許多文檔還在頁面頂部包含<style>標簽,或者分散在應用了自定義樣式的各處。 自定義樣式本身很好,但不幸的是<style>標簽本身會干擾我的 CSS 選擇器。 例如,如果我想對除第一個元素之外的每個元素應用margin-top ,我通常會使用* + * (又名“lobotomized owl”方法),這非常有效,直到有人在頂部放置了一個樣式標簽. 現在style 標簽被讀取為第一個元素,因此頁面上的每個元素都被選中。 我事先不知道元素類型; 它們可以是有效 HTML 代碼(div、span、p、table 等)的任意組合,並且還需要考慮嵌套元素 t。 我試圖修復的關鍵選擇器是以通配符 ( * + item ) 開頭的相鄰同級選擇器。

使用類似:not(style) + item是我的第一個想法,但是如果頁面中間的某個地方有任何<style>標簽,那么其中一個之后的任何元素也會被錯誤地設置樣式。

有沒有一種絕對可靠的方法可以完全使用 CSS 來做到這一點? 我無法自己編輯 HTML 文件,但如果必須的話,可以在渲染它們之前使用 Javascript 對它們進行預處理。

編輯:額外的問題,如何選擇頁面中不是<style>標簽的第一個元素? 即,我現在如何做body > *:first-child而不選擇<style>標簽?

例如,我的 CSS 文件和目標 HTML:

 div { background-color: yellow; } *+div { background-color: lime; margin-top: 1em; }
 <style> div { font-weight: bold; } </style> <div>Yellow</div> <div>Green</div> <div>Green</div> <div>Green</div> <div>Green</div>

隨着文檔布局變得更加復雜,邊距可能會變得復雜,但為了簡單起見,這個答案將假設您只需要擔心 lobobomized owls,以及具有相對簡單塊布局的文檔,其中父母和孩子之間的邊距會塌陷,因此我們可以專注於手頭的選擇器。

以下選擇器對任何數量的元素類型和任何嵌套深度(即不僅僅是body子元素)都是健壯的。 不幸的是,它確實涉及重復相同的復合選擇器:

 div, p { background-color: yellow; margin: 0; /* Remove default p margins for the sake of illustration */ } :not(style):nth-of-type(n+2), :not(style):nth-of-type(n+2) ~ * { background-color: lime; margin-top: 1em; } /* Ignore .nest elements for the sake of illustration */ .nest { background-color: transparent !important; }
 <style> div { font-weight: bold; } </style> <div>Yellow</div> <div>Green</div> <p>Green</p> <style> p { font-style: italic; } </style> <div>Green</div> <p>Green</p> <section class="nest"> <div>Yellow</div> <div>Green</div> <p>Green</p> </section>

額外的問題,如何選擇頁面中第一個不是<style>標簽的元素? 即,我現在如何做body > *:first-child而不選擇<style>標簽?

假設在第一個非style子元素之前永遠不會有多個style元素:

body > :not(style):first-child, body > style:first-child + *

如果您認為可能有多個連續style作為body的第一個子項的文檔,則需要使用此技術

body > :not(style) {
  /* Apply styles to the first non-style child */
}

body > :not(style) ~ :not(style) {
  /* Undo the above styles for following non-style children */
}

在瀏覽器開始實現級別 4 :nth-child(An+B of S)之前,沒有基於選擇器的替代方案是強大的:

/* Replaces the main answer's entire selector-list */
:nth-child(n+2 of :not(body, style))

/* Replaces the bonus question's answer */
body > :nth-child(1 of :not(style))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM