Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table Border-top only on the first row without css3

How can i use css or jquery to add border-top only on the first row in a table?

I'm using the code below to get border on every td, but i need a border for the first row on top as well.

I cannot use CSS3 in this project btw.

What i have:

content


content


content


What i want:


content


content


content


.MyCarTable td {
    border-bottom: 1px solid grey;
}
like image 317
sindrem Avatar asked Nov 06 '12 11:11

sindrem


1 Answers

Everything can be done with CSS only which is in this case preferred way becuase of performance reasons. Don't use javascript unless you actually have to because it can't be done in any other way.

Solution 1: use first-child pseudo class

Add additional style definition.

.MyCarTable td {
    border-bottom: 1px solid #ccc;
}
    .MyCarTable tr:first-child td {
        border-top: 1px solid grey;
    }

And don't worry. This particular pseudo class has been long supported in browsers. Even IE supports it since version 7. Here's a JSFiddle that shows this working.

Solution 2: table header using th elements

If your table has header row, then use th elements instead of td in it and set different styling for header cells. But use this only when semantic content of your first row cells is actually cell header description for rows underneath. Otherwise I wouldn't suggest it.

Consecutive tables problem

If you have consecutive tables within the same container then next tables get top borders from previous table's last row. And you don't want them to apply top border on first row because that duplicates borders.

The solution (as seen in this JSFiddle) is similar and also applies to first table only:

.MyCarTable td {
    border-bottom: 1px solid #ccc;
}
    .MyCarTable:first-child tr:first-child td {
        border-top: 1px solid #f99;
    }​

As you can see top row's borders are only set for first table and first row within it. All consecutive tables won't set it. This example is of course only compatible with first solution above. If you'd taken the path with th elements then a combination of both should be used (th and pseudo classes).

But as you've said you've consolidated your repeater code.

like image 126
Robert Koritnik Avatar answered Nov 15 '22 06:11

Robert Koritnik