Selectors
Web Basics — HTML & CSS Lesson 13 2:18 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Last lesson your selector was a tag name, which changes every paragraph on the page.
上一课你的选择器是一个标签名,它会改变页面上的每一个段落。
That is often too many.
那常常是太多了。
So there are two more.
所以还有另外两种。
Write a name with a dot in front and you select everything carrying that class.
写一个名字、前面加一个点,你选中的是所有带这个 class 的元素。
Write a name with a hash in front and you select the single element carrying that id.
写一个名字、前面加一个井号,你选中的是那个带这个 id 的唯一元素。
Three kinds, and the punctuation is the whole difference between them.
三种选择器,而它们之间的全部区别,就在这个标点上。
Here is the part that trips people up, and it is not really about CSS.
下面是最容易把人绊倒的地方,而它其实和 CSS 关系不大。
You write the same word twice: once on the element, as class equals note, and once in the rule, as dot note.
同一个词你要写两次: 一次写在元素上,写成 class="note"; 一次写在规则里,写成 .note。
The punctuation on one side only — the dot belongs to the selector, and it never appears in the HTML.
标点只出现在其中一边——那个点属于选择器, 它绝不会出现在 HTML 里。
Get that backwards and nothing matches, with no error message to tell you why.
弄反了就什么都匹配不上,而且没有任何报错告诉你为什么。
The other difference is how many things each one is for.
另一个区别是它们各自面向多少个元素。
A class can be on as many elements as you like — a paragraph, a list item and a div can all carry note, and one rule styles all three.
class 想加在多少个元素上都行—— 一个段落、一个列表项、一个 div 都可以带上 note, 而一条规则就能把这三个都改了。
An id is meant for one element: a page should have only one of them with any given id.
id 是为单个元素准备的: 一个页面里,同一个 id 应该只出现一次。
In practice that means you reach for almost always a class, and an id when there genuinely is only one of something, like the page's main heading.
实际写代码时,这意味着你几乎总是用 class, 只有在某样东西确实只有一个时才用 id,比如页面的主标题。
Now both tasks in one page.
现在把两道题放在同一个页面里。
The class rule turns the note green.
class 规则把那条备注变成绿色。
The id rule turns the title purple.
id 规则把标题变成紫色。
And the plain one is untouched — no class, no id, no rule that matches it.
而那个普通段落原封不动——它没有 class,没有 id,没有任何规则匹配它。
Three paragraphs, three different results, because each rule picked a different set of elements.
三个段落,三种结果, 因为每条规则选中的是不同的一组元素。
That is what a selector is for.
这正是选择器的用途。
Four things to take with you.
带走四点。
One: a bare name selects every tag of that kind.
第一:光写一个名字,选中的是那一类的所有标签。
Two: a dot selects a class, which many elements can share.
第二:点号选中的是 class,多个元素可以共用它。
Three: a hash selects an id, which belongs to one element.
第三:井号选中的是 id,它只属于一个元素。
Four: the dot and the hash go in the CSS only — on the element you write class or id as an attribute.
第四:点号和井号只写在 CSS 里—— 在元素上你写的是 class 或 id 这个属性。
Now write both rules.
现在把两条规则都写出来。