.class元素和元素.class在 CSS 中的区别

  • 本文关键字:class 元素 区别 CSS html css
  • 更新时间 :
  • 英文 :


按照本教程 http://www.w3schools.com/css/tryit.asp?filename=trycss_nesting。对为什么他们使用 .mark p 而不是 p.mark 感到困惑(为什么当我将其更改为 p.mark 时,文本不会变白)。

我浏览了以前的帖子,例如".class元素"和"元素.class"有什么区别? 但无法理解答案,因为他们使用了我不理解的术语,如孩子和后代。

有人可以提供一个关于这些工作原理的简单例子。谢谢。

它真的很简单。

采用此 HTML 代码

<div class="container">
  <div class="inner"></div>
  <div class="inner"></div>
</div>

第一种类型是元素.class

例:

div.container{
 background:red;/*This will set the background to the div WITH class "CONTAINER"*/
}

第二种类型是.class元素

例:

.container div{
   background:blue;/*This will set the background to the div INSIDE the CONTAINER class*/
}

请阅读CSS选择器的一些基本规则,如下所示:

.foo --> selects all element which have class foo
#foo --> selects an element which its id is foo
p.foo --> selects all P elements which have class foo
p#foo --> selects a P element which its id is foo
.foo p --> selects all P elements which are resident inside all elements which their class is foo
and so on...

element.class将属性应用于元素本身,而.class element将属性应用于类中的元素。

简单来说,如果你有element.class并且你说<element class="class" />那么,你制作的css将应用于该元素。另一方面,如果你有.class element,那么你就这样做

<element class="class">
<element />
</element>

然后你的CSS将应用于里面的元素。

问题是.class将属性分配给所有元素,无论其类型如何,即它可以应用于div,span,p等

但是元素.class属性仅应用于该元素

当你写.class元素名时,这意味着你在.class标签中瞄准元素名称。假设你有".test p",为此你会写, <div class="test">Happened<p>Something</p></div>

当你编写元素.class时,你试图瞄准元素标签中存在的.class元素。假设你有"p .test",为此你会写, <p>Something, <div class="test">Happened</div></p>

最新更新