1
<table>
    <tr>
        <td rowspan="2"><img src="[some image url here]"></td>
        <td>Puppy</td>
    </tr>
    <tr>
        <td>Kitten</td>
    </tr>
<table>

The code above will display a table, the first column is a picture which takes up 2 rows and the second column is composed of two rows each with a (random) word in it.

What I want to do is select the second column in the table and give each one a bottom border (I don't really want to do that, but let's use that as an example.)

So after researching I found the nth-child() pseudo-class so what I could do is:

table tr td:nth-child(2) {
    border-bottom: 1px solid gray;
}

This will work for the first row but in the second row it won't because the for the second column is the only in that so it while in the first row I can select the word 'puppy' by doing table tr td:nth-child(2) {}, in the second row I have to select it using table tr td:nth-child(1) {}.

So essentially, does anyone know a way to select the second column of a table in a situation like this without using id's or classes?

Adnan Siddiquei
  • 433
  • 1
  • 5
  • 11

3 Answers3

0

Options would include either using

table tr td:last-child {
   border-bottom: 1px solid gray;
}

Or adding a class to the td and styling that class.

I recommend that class method of approach as it's fully backwards compatible.

Chaosxmk
  • 774
  • 14
  • 28
0

Well for that specific example you could use an attribute selector like so:

HTML

<table>
    <tr>
        <td rowspan="2">Kitten</td>
        <td>Puppy</td>
    </tr>
    <tr>
        <td>Kitten</td>
    </tr>
<table>

CSS

td {
    background: green;
}

td[rowspan] {
    background: none;
}

jsFiddle

arnolds
  • 778
  • 6
  • 12
0

For that specific table in your post, you could do this:

table tr td:not([rowspan]) {
    border-bottom: 1px solid gray;
}

i.e. selecting every td which does not have a rowspan attribute.

For a more complex table (but still assuming the second column is the needed one and that the first column contains only double-row cells), you could do this:

table tr td:first-child[rowspan] + td, table tr td:first-child:not([rowspan]) {
    border-bottom: 1px solid gray;
}
andi
  • 6,442
  • 1
  • 18
  • 43