css选择器选择元素
The best way to start learning to write CSS, element selectors match the HTML tags you already know. As an example, if you want to influence the appearance of only h1
elements via a stylesheet, you can write:
开始学习编写CSS的最好方法是, 元素选择器与您已经知道HTML标记匹配。 例如,如果您想通过样式表仅影响h1
元素的外观,则可以编写:
h1 { color: firebrick; }
… in a linked or embedded stylesheet.
…在链接或嵌入的样式表中。
Element selectors – officially referred to as element type selectors – are crude, but very powerful. Common mistakes when applying them include:
元素选择器-正式称为元素类型选择器-很粗糙,但是功能非常强大。 应用它们时的常见错误包括:
The name of the selector must exactly match the name of the element.
image { … }
will not affect the appearance of<img>
tags, butimg { … }
will.选择器的名称必须与元素的名称完全匹配。
image { … }
不会影响<img>
标记的外观,但是img { … }
会影响。Be careful not to confuse the element with a common attribute when making selections.
a { … }
selects links;href
is an the attribute of the tag, not the name of the element, and can’t be used as an element selector.进行选择时,请注意不要将元素与公共属性混淆。
a { … }
选择链接;href
是标记的属性,而不是元素的名称,并且不能用作元素选择器。Avoid being caught in minutia and redundancy: work from the “largest” selector down. That is, start your stylesheet with rules for the
body
orhtml
elements, setting common colors and fonts there, using the principle of inheritance to ensure that other elements have the same appearance without having to explicitly set them. For example:body { font-family: Oxygen, sans-serif; }
is enough to ensure that almost every element on the affected page is rendered in the Oxygen font.避免陷入细节和冗余:从“最大”的选择器向下进行操作。 也就是说,从样式表的
body
或html
元素的规则开始,在其中设置通用的颜色和字体,并使用继承原理确保其他元素具有相同的外观,而不必显式设置它们。 例如:body { font-family: Oxygen, sans-serif; }
body { font-family: Oxygen, sans-serif; }
足以确保受影响页面上的几乎每个元素都以Oxygen字体呈现。- Once you have these main rules created, you don’t need to keep repeating them for other elements. 一旦创建了这些主要规则,就无需为其他元素重复这些规则。
Be aware of exceptions: changing the color of links requires that you use the specific
a
selector; trying to affect them through thebody
or other element selectors does not work. Similarly, thekbd
tag uses a reserved monospaced font when displaying its content, and won’t be affected by stylesheet font-family declarations for elements it may be inside of.注意例外:更改链接的颜色要求您使用特定
a
选择器; 试图通过body
或其他元素选择器影响它们的方法无效。 同样,kbd
标签在显示其内容时使用保留的等宽字体,并且不会受到其内部可能包含的元素的样式表字体系列声明的影响。
As a general rule, element type selectors are used to create “base” appearances for web sites, with more refined rules and exceptions left for more advanced selectors.
通常,元素类型选择器用于为网站创建“基本”外观,并为更高级的选择器保留更精细的规则和例外。
翻译自: https://thenewcode.com/811/The-Element-Type-Selector-in-CSS
css选择器选择元素