Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS to select the first 4 elements in table

Tags:

css

I want to select only the first 4 columns in the table below (highlighted in red) How do I do that?

I have tried the following so far but it's not what I wanted.

table.foobardate

table.foobardate>tr:not(:last-child)

enter image description here

Thanks!

like image 730
Tuon Can Avatar asked Dec 31 '25 07:12

Tuon Can


2 Answers

Selector nth-child(): -n to start from begin. +4 the next 4.

td:nth-child(-n+4)
like image 176
EnzoTrompeneers Avatar answered Jan 02 '26 21:01

EnzoTrompeneers


:nth-child

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

Suppose we are building a CSS grid, and want to remove the margin on every fourth grid module:

<section class="grid">
  <article class="module">One</article>
  <article class="module">Two</article>
  <article class="module">Three</article>
  <article class="module">Four</article>
  <article class="module">Five</article>
</section>

Rather than adding a class to every fourth item (e.g. .last), we can use :nth-child:

.module:nth-child(4n) {
  margin-right: 0;
}

As you can see, :nth-child takes an argument: this can be a single integer, the keywords “even” or “odd”, or a formula. If an integer is specified only one element is selected—but the keywords or a formula will iterate through all the children of the parent element and select matching elements — similar to navigating items in a JavaScript array. Keywords “even” and “odd” are straightforward (2, 4, 6 etc or 1, 3, 5 respectively). The formula is constructed using the syntax an+b, where:

“a” is an integer value
“n” is the literal letter “n”
“+” is an operator and may be either “+” or “-”
“b” is an integer and is required if an operator is included in the formula

Ref: https://css-tricks.com/almanac/selectors/n/nth-child/

like image 27
Roy Bogado Avatar answered Jan 02 '26 20:01

Roy Bogado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!