Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: How to target a specific cell inside a table?

I have a dynamically generated table and I need to style differently the 5th cell from the first row of that table.

I´m able to style the first row via:

//table.css

.mytable tbody tr:first-child { whatever styles I define.. }

Or the 5th column via:

.mytable tbody td:nth-child(5) { whatever styles I define.. }

I tried to combine this two selectors so that the cell in the 1st row, 5th column is different but without success. How can I achieve this?

like image 572
MrQ Avatar asked Sep 17 '13 09:09

MrQ


People also ask

How do you select a table cell in CSS?

There are several ways to select a table or row: Click in the table or row. Then, in the breadcrumbs (see Selecting an element) click table to select the table, or tr to select the row. Right-click a cell and from the shortcut menu, choose Table > Select or Row > Select.

How do I target a specific element in CSS?

URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element. The :target selector can be used to style the current active target element.

How do I color a specific cell in a table in HTML?

HTML | <td> bgcolor Attribute The HTML <td> bgcolor attribute is used to specify the background color of a table cell. It is not supported by HTML 5. Attribute Values: color_name: It sets the text color by using the color name.

How do I style a specific row in CSS?

If you want to apply a style to a specific column or row (but not on others), use :nth-child() property from CSS3. This selector is used to apply a style to the element number 'n' inside a parent element.


1 Answers

You can simply use the below selector

Demo

Demo 2 (Multiple Rows)

.mytable tbody tr:first-child td:nth-child(5) {
   /* Styles goes here */
}

Explanation : The above selector selects 5th td element which is nested under 1st tr element which is further nested under tbody which is further nested under ANY element having class .mytable but obviously, tbody will be used inside a table but if you want to make it specific, you can change this .mytable to table.mytable

Or you can use

.mytable tbody tr:nth-child(1) td:nth-child(5) {
   /* Styles goes here */
}

Explanation: Same as above, using nth instead of first-child

like image 56
Mr. Alien Avatar answered Oct 13 '22 20:10

Mr. Alien