[CSS]Changing the style when there are multiple consecutive th tags in a table tag.

I did a bit of tricky CSS application.
A requirement arose to change the design when there are more than five header th in a table tag, so I made some CSS.

It’s written in styled-components, but I wrote it the same way as SCSS.

目次

Apply a style when there are five or more consecutive tags below a particular element.

This style is applied to a tr directly under a tbody when there are five or more th’s within it.
Apply the style to the th tag when there are five or more elements in the tr tag with the :has pseudo-class.

const StyledTbody = styled.tbody`
  tr {
    &:has(> :nth-child(5)) th {
      color: red;
    }
  }
`;

Target consecutive tags within the first tr

Adding the :first-child pseudo-class to the tr tag will target only the first element of the tr.

const StyledTbody = styled.tbody`
  tr:first-child {
    &:has(> :nth-child(5)) th {
      color: red;
    }
  }
`;

Summary

HAS class, it is useful. But it’s not easy to understand at a quick glance, so I think it’s better to put a comment in it. Besides, if the requirement is only for this Table tag, CSS would be fine.
If there are other requirements, it would be easier to write it in JavaScript.

シェア!

この記事を書いた人

kenichiのアバター kenichi エンジニア・写真家 | Engineer and photographer

Nomadic worker who travels all over Japan and abroad; worked as a technical sales person for five years before going independent.
Works as a freelance engineer on website production and application development. Currently working to bring interesting things by interesting people to the world, while seeking to move abroad.

目次