user431806 user431806 - 1 month ago 10
CSS Question

CSS selectors: General HTML element in ID or Class Selector?

I have a div

#divWrapper
that holds a
.innerTable
table with
TD
s and
TR
s.
I would like all
TD
s insdie the #wrapper to have border-collapse: collapse and border: 1px solid black.

I was under the impression

#divWrapper td {
border-collapse: collapse;
border: 1px solid black;
}


should do the trick, but apparently the td part of the selector will apply globally, hence all TDs that have no other direct selectors will also receive the CSS.

Is there a way to construct a selector like i imagined it above ?

<div id="divWrapper ">
<table>
<tr>
<td>want border</td>
</tr>
</table>
</div>

<div>
<table>
<tr>
<td>borderless</td>
</tr>
</table>
</div>


EDIT Fiddle with actual problem
https://jsfiddle.net/ancientsion/sLt7m5nd/

Answer

The problem is with your markup.You have a space after your id,that is messing up everything

#divWrapper table tr td {
   border-collapse: collapse;
   border: 1px solid black;
}
<div id="divWrapper">
   <table>
    <tr>
     <td>want border</td>
    </tr>
   </table>
</div>

<div>
   <table>
    <tr>
     <td>borderless</td>
    </tr>
   </table>
</div>

Your solution to the problem mentioned in the fiddle. If you want to select only those td's within #wrapper ,then it should be

wrapper table tr td ,but you have given it as #wrapper th,td this selects all th elements within wrapper and all td's in the wrapper and outside

check the following solution

#wrapper table th,#wrapper table td {
  border: 1px solid black;
}
<div id=wrapper>
  <table>
    <tr>
      <th>

        header1

      </th>
      <th>

        header2


      </th>
    </tr>

    <tr>
      <td>
        One
      </td>
      <td>
        two
      </td>
    </tr>
    <tr>
      <td>
        line2
      </td>
      <td>
        cell 2
      </td>
    </tr>
  </table>
</div>

<br>
<br>

<table>
  
    <th>
      TH
    </th>
  <tr>
    <td style="color: red;">
      TD
    </td>
  </tr>
</table>

Hope this makes you understand for more reference http://www.w3schools.com/cssref/css_selectors.asp

Comments