用标签为奇数行和偶数行设置不同的背景颜色
时间: 2023-12-14 09:38:41 浏览: 65
可以使用CSS中的nth-child选择器来实现。具体实现方式如下:
```html
<style>
/* 奇数行的背景色为蓝色 */
tr:nth-child(odd) {
background-color: blue;
}
/* 偶数行的背景色为红色 */
tr:nth-child(even) {
background-color: red;
}
</style>
<table>
<tr>
<td>第一行</td>
</tr>
<tr>
<td>第二行</td>
</tr>
<tr>
<td>第三行</td>
</tr>
<tr>
<td>第四行</td>
</tr>
<tr>
<td>第五行</td>
</tr>
</table>
```
这样,表格中的奇数行背景色就会变为蓝色,偶数行背景色就会变为红色。
相关问题
用foreach标签为奇数行和偶数行设置不同的背景颜色
假设你的数据是一个数组 `$data`,你可以这样使用 `foreach` 标签为奇数行和偶数行设置不同的背景颜色:
```html
<table>
<tr>
<th>标题1</th>
<th>标题2</th>
<th>标题3</th>
</tr>
{% foreach $data as $key => $row %}
{% if $key % 2 == 0 %}
<tr style="background-color: #e6e6e6;">
{% else %}
<tr>
{% endif %}
<td>{{ $row['col1'] }}</td>
<td>{{ $row['col2'] }}</td>
<td>{{ $row['col3'] }}</td>
</tr>
{% endforeach %}
</table>
```
在上面的例子中,我们使用了 `$key` 来获取当前循环的索引,然后通过判断 `$key % 2` 是否等于 0 来区分奇数行和偶数行。如果是偶数行,则为该行设置灰色背景,否则不设置背景色。
javaweb为表单奇数行偶数行设置不同背景色,css和jsp具体代码
可以使用CSS的伪类选择器nth-child(n)来实现,具体代码如下:
```css
tr:nth-child(odd) {
background-color: #f2f2f2; /*奇数行颜色*/
}
tr:nth-child(even) {
background-color: #ffffff; /*偶数行颜色*/
}
```
在JSP页面中,可以将以上CSS代码嵌入到<style>标签中,然后在表格的<tr>标签中应用class属性即可。
```jsp
<style>
tr:nth-child(odd) {
background-color: #f2f2f2; /*奇数行颜色*/
}
tr:nth-child(even) {
background-color: #ffffff; /*偶数行颜色*/
}
</style>
<table>
<tr class="odd">
<td>第一行</td>
</tr>
<tr class="even">
<td>第二行</td>
</tr>
<tr class="odd">
<td>第三行</td>
</tr>
<tr class="even">
<td>第四行</td>
</tr>
</table>
```
在上面的代码中,我们为奇数行设置了class="odd",为偶数行设置了class="even",然后在CSS中使用nth-child选择器来设置不同的背景颜色。