tables | col & colgroup

Hey, how do the col and colgroup tags work? It's not too clear too me, i'd appreciate any explanation, thanks in advance.
6 Replies
Chooβ™šπ•‚π•šπ•Ÿπ•˜
The <colgroup> is used as a container for the <col> tags, and the <col> tags are for enabling the ability to apply a class to entire columns within a table without placing class names on every <td> directly.
snxxwyy
snxxwyyOPβ€’6mo ago
ah okay that makes sense. I was taking a look at the mdn example (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col) and colgroup looks out of place to me without a structure of thead, tbody and tfoot, I'm just not sure where it fits in and how it manages to control the td in the same column etc.
MDN Web Docs
: The Table Column element - HTML: HyperText Markup Language | MDN
The HTML element defines one or more columns in a column group represented by its parent element. The element is only valid as a child of a element that has no span attribute defined.
Chooβ™šπ•‚π•šπ•Ÿπ•˜
You have to look at the span attribute of the <col> for it to make sense. In the Batman/Flash example, there is 1 <col> without a span and 2 <col> that each have a span of 2. That matches the 5 columns that are in the table. The first column is not assigned a class. The second and third are in the batman class and the fourth and fifth are in the flash class. Nesting would have made more sense, but that isn't how the spec was written.
snxxwyy
snxxwyyOPβ€’6mo ago
oh okay that makes more sense, thank you. So let's say you give a col a certain style like background-color it styles everything such as td and th within the same column? i just have two more questions: 1. Where would you place a colgroup it if everything was structured? Let's say you had the below as an example, would you put it where i have? or does it need to be nested in something like a tr?
<table>
<caption>...</caption>
<colgroup>...</colgroup>
<thead>...</thead>
<tbody>...</tbody>
<tfoot>...</tfoot>
</table>
<table>
<caption>...</caption>
<colgroup>...</colgroup>
<thead>...</thead>
<tbody>...</tbody>
<tfoot>...</tfoot>
</table>
2. Is using colgroup and col a common practice and recommended to do so? Or do people now use nth-type/child selectors to style columns? I've seen a bit of both.
Chooβ™šπ•‚π•šπ•Ÿπ•˜
Yes. 1) That structure works. 2) It's a very old technique. I think nth-child is more popular now.
snxxwyy
snxxwyyOPβ€’6mo ago
ah awesome, i understand everything now, i appreciate your help, thanks
Want results from more Discord servers?
Add your server