8

So, I am a bit confused over this simple thing, i've googled as much as i could, but i just dont know the right keywords for googling it, i tried CSS selectors, etc, no answer was enough to clear my confusion. So i've also tested and p.classname doesn't even seem to work, but by definition in a book i'm reading ( updated 2012 )

To create a class in CSS and select an element in that class, you write a class selector, like this:

p.classname{ stuff }

So now you have a way of selecting

elements that belong to a certain class to style them.

I couldn't find a definition for

classname p, but myself would give something like this definition "select all p elements that belong to classname", which is basicly the same.

the p.classname works when i give the "classname" to a im still confused, at the moment i would suppose im just going to perma use the .classname p, which works and is basically the same.

So, please help me out to clear this confusion, i've googled, i tried to help this confusion but it didn't work, it only made more.

Thanks

4

3 回答 3

20

所以当你这样做时

p.classname{
  ... 
}

你正在寻找一个<p>与类classname

当你这样做时

.classname p

您正在寻找一个p 是 classes 的后代classname

在 CSS.中用作类名的选择器。

于 2013-04-18T22:05:43.817 回答
2

CSS 通过按顺序读取每个规则来工作,例如。

p {font-weight: bold;}

p span {font-weight:normal;}

<p>Hiya</p> // BOLD

<p><span>HIYA</span></p> // NORMAL

上课也一样

.bold {font-weight: bold;}

span {font-weight:normal;}

<p class="bold">I AM BOLD <span>I AM NOT</span> BOLD AGAIN</p>

<p class="bold"><span> I AM ALL NORMAL</span></p>

因此,在您的示例中,定义classfirst 将针对具有该类的每个元素。

通过在该类之后定义某些内容,.class p它将针对该类中的所有元素 p。

希望这有帮助

更新

让你更好地理解,

div {color: blue;}
div p {color: red;}
div p span {color: yellow;}
div ul {color: purple;}

<div>I AM BLUE <p>I AM RED <span> I AM YELLOW</span></p>I AM BLUE</div>

<p>I HAVE NO CSS ATTACHED TO ME</p>

<div><ul><li>I AM PURPLE</li></ul> I AM BLUE</div>

它对类的作用与对元素的作用完全相同。

于 2013-04-18T22:08:58.803 回答
1

如果你有以下 CSS,我会这样解释:

p.classname { stuff }

它只将该类名锁定到<p>标签。

因此,如果您放入任何其他内容,则除了标签class="classname"之外,它不会对任何其他内容起作用。<p>

于 2020-09-01T13:48:41.817 回答