arvid arvid - 1 month ago 9
CSS Question

Changing the order of comma-separated selectors breaks styling

If I change the order of elements in a sub selector it affects an element outside of the class.

Common HTML:

<input type='text'>
<hr>
<table class="mytable">
<tbody>
<tr><td><input type='text'></td></tr>
<tr><td><input type='text'></td></tr>
<tr><td><input type='text'></td></tr>
</tbody>
</table>


This CSS works (jsfiddle):

input {
margin: 0 0 2em;
}
table.mytable input,select,a {
margin: 0;
}


The following CSS causes the first input before the table to lose its margin simply by placing
<select>
first in the sublist of elements (jsfiddle). That is the mytable class is activated (selected) for the first input box when it should not be.

input {
margin: 0 0 2em;
}
table.mytable select,input,a {
margin: 0;
}


I tested this in both Chrome and Firefox and they both act the same way. So is this a bug? or Can someone explain what I am missing?

Answer

The way your CSS is written doesn't work in "sub-sets" as you may have hoped.

By placing select first, you've inadvertently now removed the margin from ALL inputs.

The way you have it now, if I were to break it apart would look like this:

input {
    margin: 0 0 2em;
}

table.mytable input {
    margin: 0;
}

select {
    margin: 0;
}

a {
    margin: 0;
}

To get it to work the way you want, you need to include table.mytable with each of the "subsets" you want after each comma.

input {
     margin: 0 0 2em;
}

table.mytable select,
table.mytable input,
table.mytable a {
    margin: 0;
}
Comments