序言
过去很怕写CSS,感觉毫无逻辑。最近感觉不会CSS真的很蛋疼,比如会有很多奇葩的问题诸如:“CSS中,两个class类之间有空格和没空格的区别是什么?”。所以整理了一下常见的几种情况。
实例HTML代理
<h1 class="important"> This heading is very important. </h1> <p class="important"> This paragraph is very important. </p>
结合元素选择器
只有段落显示为红色文本:
p.important {color:red;}
选择器现在会匹配 class 属性包含 important 的所有 p 元素,但是其他任何类型的元素都不匹配,不论是否有此 class 属性。选择器 p.important 解释为:“其 class 属性值为 important 的所有段落”。 因为 h1 元素不是段落,这个规则的选择器与之不匹配,因此 h1 元素不会变成红色文本。
CSS 多类选择器
class类不包含空格
其实这个就对应“CSS中,两个class类之间有空格和没空格的区别是什么?”这个问题,比如如下HTML
<h1 class="important warning"> This heading is very important. </h1> <p class="important"> This paragraph is very important. </p>
这两个词的顺序无关紧要,写成 warning important 也可以。
我们假设 class 为 important 的所有元素都是粗体,而 class 为 warning 的所有元素为斜体,class 中同时包含 important 和 warning 的所有元素还有一个银色的背景 。就可以写作:
.important {font-weight:bold;}
.warning {font-style:italic;}
.important.warning {background:silver;}
class类包含空格
如果html类似如下结构:
<h1 class="important"> <span class="warning">This heading is very important.</span> </h1> <p class="important"> This paragraph is very important. </p>
这样css的两个class就包含空格,可以写做:
.important .warning {background:silver;}