p.classname or .classname p, any difference?

2019-02-15 18:19发布

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

2条回答
Summer. ? 凉城
2楼-- · 2019-02-15 18:53

CSS works by reading each rule in order, example.

p {font-weight: bold;}

p span {font-weight:normal;}

<p>Hiya</p> // BOLD

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

Same goes for classes

.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>

So in your example defining a class first will target each and every element that has that class.

By defining something after that class .class p it will target all elements inside that class which are p.

Hope this helped

UPDATE

so you can understand better,

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>

It works exactly the same for classes as it does with elements.

查看更多
放荡不羁爱自由
3楼-- · 2019-02-15 19:02

So when you do

p.classname{
  ... 
}

You are looking for a <p> with class classname

when you do

.classname p

You are looking for a p that is a descendant of the classes classname.

In CSS . is used as a selector for a class name.

查看更多
登录 后发表回答