006_CSS类选择器
1. CSS类选择器
1.1. 类选择器允许以一种独立于文档元素的方式来指定样式。
1.2. 该选择器可以单独使用, 也可以与其他元素结合使用。
1.3. 只有适当地标记文档后, 才能使用这些选择器。
1.4. 要应用样式而不考虑具体设计的元素, 最常用的方法就是使用类选择器。
2. 修改html代码
2.1. 在使用类选择器之前, 需要修改具体的文档标记, 以便类选择器正常工作。
2.2. 为了将类选择器的样式与元素关联, 必须将class指定为一个适当的值。请看下面的html代码:
<h1 class="important"> This heading is very important. </h1><p class="important"> This paragraph is very important. </p>2.3. 在上面的代码中, 两个元素的class都指定为important: 第一个标题(h1 元素), 第二个段落(p 元素)。
2.4. 例子
2.4.1. 代码
<!DOCTYPE html> <html><head><title>CSS类选择器</title><meta charset="utf-8" /><style type="text/css">.important {color: red;}</style></head><body><h1 class="important">This heading is very important.</h1><p class="important">This paragraph is very important.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>...</p></body> </html>2.4.2. 效果图
3. 语法
3.1. 然后我们使用以下语法向这些归类的元素应用样式, 即类名前有一个点号(.), 然后结合通配选择器:
*.important {color: red; }3.2. 如果您只想选择所有类名相同的元素, 可以在类选择器中忽略通配选择器, 这没有任何不好的影响:
.important {color: red; }4. 结合元素选择器
4.1. 类选择器可以结合元素选择器来使用。
4.2. 例如, 您可能希望只有段落显示为红色文本:
p.important {color: red; }4.3. 选择器现在会匹配class属性包含important的所有p元素, 但是其他任何类型的元素都不匹配, 不论是否有此class属性。选择器p.important解释为:"其class属性值为important的所有段落"。因为h1元素不是段落, 这个规则的选择器与之不匹配, 因此h1元素不会变成红色文本。
4.4. 例子
4.4.1. 代码
<!DOCTYPE html> <html><head><title>CSS类结合元素选择器</title><meta charset="utf-8" /><style type="text/css">p.important {color: red;}</style></head><body><h1 class="important">This heading is very important.</h1><p class="important">This paragraph is very important.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>...</p></body> </html>4.4.2. 效果图
5. CSS多类选择器
5.1. 在html中, 一个class值中可能包含一个词列表, 各个词之间用空格分隔。例如, 如果希望将一个特定的元素同时标记为重要(important)和警告(warning), 就可以写作:
<p class="important warning"> This paragraph is a very important warning. </p>5.2. 这两个词的顺序无关紧要, 写成warning important也可以。
5.3.我们假设class为important的所有元素都是粗体, 而class为warning的所有元素为斜体, class中同时包含important和warning的所有元素还有一个银色的背景。就可以写作:
.important {font-weight: bold; } .warning {font-style: italic; } .important.warning {background: silver; }5.4. 通过把两个类选择器链接在一起, 仅可以选择同时包含这些类名的元素(类名的顺序不限)。
5.5. 例子
5.5.1. 代码
<!DOCTYPE html> <html><head><title>CSS多类选择器</title><meta charset="utf-8" /><style type="text/css">.important {font-weight: bold;}.warning {font-style: italic;}.important.warning {background: silver;}</style></head><body><p class="important">This paragraph is very important.</p><p class="warning">This is a warning.</p><p class="important warning">This paragraph is a very important warning.</p><p>This is a paragraph.</p><p>...</p></body> </html>5.5.2. 效果图
总结
以上是生活随笔为你收集整理的006_CSS类选择器的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 005_CSS通配符选择器
- 下一篇: 007_CSS ID选择器