一css类选择器概述
类选择器允许以一种独立于文档元素的方式来指定样式。该选择器可以单独使用,也可以与其他元素结合使用。
只有适当地标记文档后,才能使用这些选择器,所以使用这两种选择器通常需要先做一些构想和计划。要应用样式而
不考虑具体设计的元素,最常用的方法就是使用类选择器。
二修改 HTML 代码
立即学习“前端免费学习笔记(深入)”;
在使用类选择器之前,需要修改具体的文档标记,以便类选择器正常工作。为了将类选择器的样式与元素关联,
必须将 class 指定为一个适当的值。
请看下面的 HTML 代码:
<h1 class="important">This heading is very important.</h1><p class="important">This paragraph is very important.</p>
三CSS类选择器语法
然后我们使用以下语法向这些归类的元素应用样式,即类名前有一个点号(.),然后结合通配选择器:
*.important {color:red;}.important {color:red;}浏览器显示的结果为:
四结合元素选择器
类选择器可以结合元素选择器来使用。
例如,您可能希望只有段落显示为红色文本:
p.important {color:red;}class 属性。选择器 p.important 解释为:“其 class 属性值为 important 的所有段落”。 因为 h1 元素不是段落,这个
规则的选择器与之不匹配,因此 h1 元素不会变成红色文本。
浏览器显示的结果为:
如果你确实希望为 h1 元素指定不同的样式,可以使用选择器 h1.important:
p.important {color:red;}h1.important {color:blue;}.important {color:red;}在上述描述中,我们处理了 class 值中包含一个词的情况。在 HTML 中,一个 class 值中可能包含一个词列表,
各个词之间用空格分隔。
例如,如果希望将一个特定的元素同时标记为重要(important)和警告(warning),就可以写作:
<p class="important warning">This paragraph is a very important warning.</p>
我们假设 class 为 important 的所有元素都是粗体,而 class 为 warning 的所有元素为斜体,class 中同时包含
important 和 warning 的所有元素还有一个银色的背景 。就可以写作:
.important {font-weight:bold;}.warning {font-weight:italic;}.important.warning {background:silver;}通过把两个类选择器链接在一起,仅可以选择同时包含这些类名的元素(类名的顺序不限)。如果一个多类选择
器包含类名列表中没有的一个类名,匹配就会失败。
请看下面的规则:
.important.urgent {background:red;} class 属性中只有词 important 和 warning,将不能匹配。不过,它能匹配以下元素:
<p class="important urgent warning">This paragraph is very important.</p>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title><style type="text/css">.important {font-weight:bold;}.warning {font-weight:italic;}.important.warning {background:silver;}.important.urgent {background:red;}</style></head><body> <p class="important">This paragraph1 is very important.</p> <p class="warning">This paragraph2 is very important.</p> <p class="important warning">This paragraph3 is very important.</p> <p class="important urgent">This paragraph4 is very important.</p> <p class="important urgent warning">This paragraph5 is very important.</p></body></html>浏览器显示的结果为:
版权声明:本文为博主原创文章,未经博主允许不得转载。
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号