开发者

CSS different color for table each line

I have this table with the following CSS formatting:

<table cellspacing="2">
    <tbody>
        <tr>
            <th>Name</th>                            
            <th>Area</th>                            
        </tr>
        <tr>
            <td>${it.conference}</td>                                              
            <开发者_StackOverflow社区;td>${it.accepted}</td>                                      
        </tr>
    </tbody>
</table>

And CSS:

table {
    padding-left: 10px;
    width:90%;
    font-family:Arial, Helvetica, sans-serif;
    font-size:11px;
    text-align:left;
}

th, td {
    padding:5px 10px;
}

th {
    color:#666666;
    border-top:2px solid #b7ddf2;
    background-color:#ebf4fb;
}

How can i apply individual css modifications for each line (for example, I would like to change the color of 'Name', without messing up with the other lines formatting, which means, only modify that one. Is that possible to do?


Are you looking for something similar to the nth-child CSS pseudo-class?

If you want a more fine grain control over each individual one you might want to consider applying classes to them and styling them differently.

Edit: Here are a few examples of nth-child.


With a CSS only method you'll need to add some class to the line you would like to style, like this:

<table cellspacing="2">
      <tbody><tr>
         <th class="color1">Name</th>                            
         <th>Area</th>                            
     </tr>
        <td>${it.conference}</td>                                              
        <td>${it.accepted}</td>                                      
     </tr></tbody>
    </table>

and then style it:

.color1 {
   background-color: (somecolor);
}


To style "Even" & "Odd" rows then use CSS3 like:

tr:nth-child(odd){
    background:#999;}

tr:nth-child(even){
    background:#f5f5f5;}


If you can get away without support for IE 7 and 8, you can do...

th:nth-of-type(1) {
  color: #c00;
}

Otherwise, add a class such as th class="whatever" and then...

th.whatever {
  color: #c00;
}

See a live demo:

http://jsfiddle.net/GFPgB/


If you want to apply CSS style based on the content of the element, that is not possible with CSS. If on the other hand you want to apply CSS styles based on their position, you can use the :nth-child(N) pseudo classes. For example

th:nth-child(1) /*for name*/
{
color: blue;
}

th:nth-child(2) /*for area*/
{
color: red;
}


apply a class to whatever element you want, and CSS style it. http://jsfiddle.net/robx/wzXAJ/ IE: apply <th class="name">Name</th>.


I know this is an old answer, but I made a fun example in Jquery, and maybe it will help somebody with their question.

JSFIDDLE

It'll get all <p> elements from the document and will loop through them, as jquery does that, it will add a CSS style to every <p> element on the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜