coderighton coderighton - 1 month ago 14
CSS Question

HTML first table column how to inverse "td + td"?

I'm building a table similar to this:



<head>
<style>
td + td {
background-color: red
}
</style>
</head>

<body>
<table style="border: solid 1px black">
<tr>
<td>content</td>
<td>content</td>
<td>content</td>
</tr>
<tr>
<td>content</td>
<td>content</td>
<td>content</td>
</tr>
<tr>
<td>content</td>
<td>content</td>
<td>content</td>
</tr>
</table>
</body>





using "td + td" to select everything BUT the first column, which works just fine for me.

<head>
<style>
td + td {
background-color: red
}
</style>
</head>


Now inversing what "td + td" does by using "td:first-child" works fine, too:



<head>
<style>
td:first-child {
background-color: red
}
</style>
</head>

<body>
<table style="border: solid 1px black">
<tr>
<td>content</td>
<td>content</td>
<td>content</td>
</tr>
<tr>
<td>content</td>
<td>content</td>
<td>content</td>
</tr>
<tr>
<td>content</td>
<td>content</td>
<td>content</td>
</tr>
</table>
</body>





however I'm looking for a way to turn "td + td" around (inverse/reverse) to do the same "td:first-child" does. In other words I'm looking for something like "td - (td + td)" which is not actually a working piece of code. So I can put it into the
<style></style>
tags in my HTML file.

Searching for a solution didn't get me anywhere so here I am, hi.

EDIT:

there are basically two outcomes which can be achieved here:

- selecting everything BUT the first column

and

- selecting the first column ONLY

Both can be approached differently. So far I've learned about two ways to go for

"select all BUT first column"

1. "td + td"


2. "td:nth-child"


and one way to go for

"select first column ONLY"

1. "???"


2. "td:first-child"


I'm missing the counterpart of "td + td" without using any version of :nth-child or :type etc. (looking for a no-colon version, like "td + td" is).

Why? Learning more ways to approach things to improve my overall coding skills.

Answer

As you already know, td + td means the style applies only to table cells directly following another table cells -> adjacent selector

To Note:

directly following

There is NO css selector to apply to elements which are just before another element (reverse of above - previous sibling selector).

Reason:

When a browser get a set of adjacent elements which it has to stack on the page, it goes in the order in which they appear in the HTML.
Source: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_without_z-index

css selectors are designed to be easy (fast) to implement for the browser. The document can be traversed once, matching elements as you go, with no need to ever go backward to adjust a match

Comments