5

I am trying to simplify my css selector in CSS sheet

I have something like

.table_test .div, .table_name .div, .table_company .div{
    color:black;
}


.table_test .div table input, .table_name .div table input{
    color:red;
}

My html is something like

<div class='table_test'>
  <div class='div'>......
  <table>
   <tr>
    <td><input>...</td> 
   </tr>
  </table>
</div>

<div class='table_name'>
  <div class='div'>......
  <table>
   <tr>
    <td><input>...</td> 
   </tr>
  </table>
</div>

I feel like there are so many selectors clustered together and was wondering if there is a way to make it simpler. Thanks for the help!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

3 Answers3

5

A few things:

Don't use generic class names like div. There's already an element element called div. If you want to target it based on nesting, do so using CSS.

.table_name > div {} /* or .table_name div */

And not...

.table_name .div {}

Use specific selectors. Is there a reason why you need to go through table_name .div table input? Why not target the input specifically by giving it a class?

<input class="my_input">

And then:

.my_input {
  color: red;
}

Finally, it's up to you what style to use, but most people tend to use double quotes around html attributes. For example:

<div class="table_name"> and not <div class='table_name'>

Mohamad
  • 34,731
  • 32
  • 140
  • 219
1

You could create a class name that tables that are the same style would share

CSS

.similar-table .div{
    color:black;
}


.similar-table input{
    color:red;
}

HTML

<div class='table_test similar-table'>
  <div class='div'>......
  <table>
   <tr>
    <td><input>...</td> 
   </tr>
  </table>
</div>

<div class='table_name similar-table'>
  <div class='div'>......
  <table>
   <tr>
    <td><input>...</td> 
   </tr>
  </table>
</div>
mikes000
  • 678
  • 6
  • 11
0

CSS:

.red{
  color:red;
}
.black{
  color:black;
} 

HTML:

<div class='table_test'>
 <div class='div'>......
  <table>
   <tr>
    <td><input class="black">...</td> 
   </tr>
 </table>
</div>

<div class='table_name'>
 <div class='div'>......
  <table>
   <tr>
    <td><input class="red">...</td> 
   </tr>
  </table>
</div>

The best part? This CSS will work wherever you need it to.

Community
  • 1
  • 1
Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96
  • 5
    Class names like `red` and `float-left` defeat the point of CSS a little. I have definitely seen people do stuff like `.blue-text {color:black !important}` and other such nonsense. – Wesley Murch Aug 19 '13 at 23:39
  • That may be, but these were example class names not intended for actual use. I presumed the OP's `.div` was the same. At least I hope it was... – Chris Sobolewski Aug 20 '13 at 02:08