Jacob
Jacob

Reputation: 4031

CSS correct class selector undestanding

Now I have my code in this way;

CSS:

.dhimage{
 width:25px;
 height:25px;
}

JAVASCRIPT:

var image = document.createElement('img');
image.className= 'dhimage';

What changes if i format CSS like this:

.something .dhimage{
 width:25px;
 height:25px;
}

Upvotes: 1

Views: 43

Answers (2)

Manish Mishra
Manish Mishra

Reputation: 12375

it means, your newly created image has to be inside a container having class something, only then the properties of class dhimage will be applied to it. i.e

<div class="something" >
   <img class="dhimage" />
</div>

if your markup is like above, then only below css will work

.something .dhimage
{
   width:25px;
   height:25px; 
}

it is called CSS specificity .

however, if you directly define the css i.e.

.dhimage
{
   width:25px;
   height:25px; 
}

it will work independent of the parent's CSS.

Now why is it done.

say you have a class name menu. but you want the menu class to be different for menus inside the footer of your page and different for the menus inside header of your page,but still you want to keep the name menu because you also have certain common rules for all the menus on the site like font-family or whatever. then you can define it as follows:

.menu
{
   font-family:'Times';
}
.header .menu
{
  color:Red;
}
.footer .menu
{
  color:Orange;
}

and your markup is like

<div class="header">
  <ul class="menu">
  </ul>
</div>

<div class="content">
</div>

<div class="footer">
  <ul class="menu">
  </ul>
</div>

your header and footer menu will have different color.

Upvotes: 2

Xenolithic
Xenolithic

Reputation: 210

Nothing, really, except for the fact that, in order for the styling from .dhimage to be effective, the element containing that class must be inside an element with the class .something.

Upvotes: 1

Related Questions