Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do commas and spaces in multiple classes mean in CSS?

.container_12 .grid_6,
.container_16 .grid_8 {
    width: 460px;
}

That says "make all .grid_6's within .container_12's and all .grid_8's within .container_16's 460 pixels wide." So both of the following will render the same:

<div class="container_12">
  <div class="grid_6">460px Wide</div>
</div>
<div class="container_16">
  <div class="grid_8">460px Wide</div>
</div>

As for the commas, it's applying one rule to multiple classes, like this.

.blueCheese, .blueBike {
  color:blue;
}

It's functionally equivalent to:

.blueCheese { color:blue }
.blueBike { color:blue }

But cuts down on verbosity.


.container_12 .grid_6 { ... }

This rule matches a DOM node with class container_12 that has a descendant (not necessarily a child) with class grid_6, and applies the CSS rules to the DOM element with class grid_6.

.container_12 > .grid_6 { ... }

Putting > between them says that the grid_6 node must be a direct child of the node with class container_12.

.container_12, .grid_6 { ... }

A comma, as others have stated, is a way to apply rules to many different nodes at one time. In this case, the rules apply to any node with either a class of container_12 or grid_6.


Not exactly what was asked, but maybe this will help.

To apply a style to an element only if it has both classes your selector should use no space between the class names.

For Example:

.class1.class2 { color: #f00; }
.class1 .class2 { color: #0f0; }
.class1, .class2 { font-weight: bold; }
<div class='class1 class2'>Bold Red Text</div>
<div class='class1'>Bold Text (not red)</div>
<div class='class1'><div class='class2'>Bold Green Text</div></div>

Comma groups the classes (applies the same style to them all), an empty space tells that the following selector must be within the first selector.

Therefore

.container_12 .grid_6,
.container_16 .grid_8 {
    width: 460px;
}

applies that style to only class .grid_6 which is within .container_12 class and to .grid_8 class which is within .container_16.


The width: 460px; will be applied to the element with the .grid_8 class, contained inside the elements with .container_16 class, and elements with the .grid_6 class, contained inside the elements with .container_12.

The space means heritage, and the comma means 'and'. If you put properties with a selector like
.class-a, .class-b, you will have the properties applied to the elements with anyone of the two classes.

Hope I have helped.