問題描述
在 CSS 中,*
將匹配任何元素.
In CSS, *
will match any element.
經常使用 *|*
代替 *
來匹配所有元素.這通常用于測試目的.
Frequently, *|*
is used instead of *
to match all elements. This is generally used for testing purposes.
*
和*|*
在CSS中有什么區別?
What is the difference between *
and *|*
in CSS?
推薦答案
根據 W3C選擇器規范:
通用選擇器允許一個可選的命名空間組件.用法如下:
The universal selector allows an optional namespace component. It is used as follows:
ns|*
命名空間 ns 中的所有元素
ns|*
all elements in namespace ns
*|*
所有元素
|*
所有沒有命名空間的元素
|*
all elements without a namespace
*
如果沒有指定默認命名空間,這相當于 *|*.否則,它等效于 ns|*,其中 ns 是默認命名空間.
*
if no default namespace has been specified, this is equivalent to *|*. Otherwise it is equivalent to ns|* where ns is the default namespace.
所以,沒有 *
和 *|*
并不總是相同的.如果提供了默認名稱空間,則 *
僅選擇屬于該名稱空間的元素.
So, no *
and *|*
are not always the same. If a default name space is provided then *
selects only elements that are part of that namespace.
您可以使用以下兩個片段直觀地看到差異.首先,定義了默認命名空間,因此 *
選擇器僅將米色背景應用于作為該命名空間一部分的元素,而 *|*
應用所有元素的邊框.
You can visually see the differences using the below two snippets. In the first, a default namespace is defined and so the *
selector applies the beige colored background only to the element which is part of that namsepace whereas the *|*
applies the border to all elements.
@namespace "http://www.w3.org/2000/svg";
* {
background: beige;
}
*|* {
border: 1px solid;
}
<a href="#">This is some link</a>
<svg xmlns="http://www.w3.org/2000/svg">
<a xlink:href="#">
<text x="20" y="20">This is some link</text>
</a>
</svg>
在下面的代碼片段中,沒有定義默認命名空間,因此 *
和 *|*
都適用于所有元素,因此所有元素都獲得米色背景和黑色邊框.換句話說,當沒有指定默認命名空間時,它們的工作方式相同.
In the below snippet no default namespace is defined and so both *
and *|*
applies to all elements and so all of them get both the beige background and the black border. In other words, they work the same way when no default namespace is specified.
* {
background: beige;
}
*|* {
border: 1px solid;
}
<a href="#">This is some link</a>
<svg xmlns="http://www.w3.org/2000/svg">
<a xlink:href="#">
<text x="20" y="20">This is some link</text>
</a>
</svg>
正如 BoltClock 在評論中指出的那樣 (1,2),最初命名空間僅適用于基于 XML 的語言,例如 XHTML、SVG 等,但根據最新規范,所有 HTML 元素(即 HTML 命名空間中的元素)都被命名為 http://www.w3.org/1999/xhtml
.Firefox 遵循這種行為,并且在所有 HTML5 用戶代理中都是一致的.您可以在此答案中找到更多信息.
As BoltClock points out in comments (1,2), initially namespaces applied only to XML based languages such as XHTML, SVG etc but as per latest specs, all HTML elements (that is, elements in the HTML namespace) are namespaced to http://www.w3.org/1999/xhtml
. Firefox follows this behavior and it is consistent across all HTML5 user agents. You can find more information in this answer.
這篇關于CSS 中的 * 和 *|* 有什么區別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!