如何选择性地应用具有重叠元素引用的两个CSS样式块



假设我有这个:

table, th, td {
border: 1px solid white;
border-collapse: collapse;
}
th, td {
background-color: #96D4D4;
}

请注意,我有这两个CSS块,它们有重叠的引用(它们都引用th和td(。假设我有两张桌子,那么:

<table>
<tr>
<td>This is one table, no formatting</td>
<tr>
</table>
<table>
<tr>
<td>This is another table, to which I want to apply formatting.</td>
<tr>
</table>

如何仅将CSS样式应用于底部表格?以下是我迄今为止所尝试的:

尝试1:将所有属性集中到一个样式中,并将其放入<div>

.betterformat {
border: thin groove blue;
border-collapse: collapse;
background-color: red;
}
<div class="betterformat">
<--Here's all my <table> <tr> and <td> tags...--
</div>

这不起作用,所以我认为

尝试2:为表和tr/td创建两个单独的类

但不,我知道为每个单独的<tr><td>标签遍历和设置类是很耗时的,显然不是这样做的。对于将来的参考,有没有一个好的页面可以解释重叠引用在CSS中是如何工作的,类是如何与它交互的,也许还有ID之类的东西?

使用类选择器指定CSS类型选择器(在您的情况下betterformat:

<style>
.betterformat table,
.betterformat th,
.betterformat td {
border: 1px solid white;
border-collapse: collapse;
}

.betterformat th,
.betterformat td {
background-color: #96D4D4;
}
</style>

<table>
<tr>
<td>This is one table, no formatting</td>
<tr>
</table>
<div class="betterformat">
<table>
<tr>
<td>This is another table, to which I want to apply formatting.</td>
<tr>
</table>
</div>

我会为每个表分配一个不同的类,然后根据需要设置类的样式:

.table1 {
border: 1px solid red;
}
.table1 td {
color: green;
}
.table2 {
border: 1px solid blue;
}
.table2 td {
color: orange;
}
<table class="table1">
<tr>
<td>This is one table.</td>
<tr>
</table>
<br>
<table class="table2">
<tr>
<td>This is another table.</td>
<tr>
</table>

最新更新