如何使用CSS或HTML粗体化特定的HTML行和列?

时间:2014-06-11 03:51:06

标签: html css html-table

我想加粗HTML表格的第一行和第一列(第0行和第0列)。如何用HTML或CSS完成?

表格:

<table border="1">
    <tbody>
        <tr>
            <td></td>
            <td>translate.com AND https://translate.google.com/</td>
            <td>http://www.bing.com/translator/</td>
        </tr>
        <tr>
            <td>I eat tacos</td>
            <td>Yo como tacos</td>
            <td>Comer tacos</td>
        </tr>
    . . .
    </tbody>
</table>

...和CSS:

body {
    font-family: "Segoe UI", "Calibri", "Candara", "Bookman Old Style", "Consolas", sans-serif;
    font-size: 1.2em;
    color: navy;
}

......非常基本。

表格在这里:http://jsfiddle.net/clayshannon/LU7qm/7/

2 个答案:

答案 0 :(得分:8)

要使用CSS加粗第一行和第一列,使用当前的HTML标记,请使用:first-child伪类,该类匹配作为其父级的第一个子元素(第一个子元素)的任何元素:

tr:first-child, td:first-child { font-weight: bold }

但是,如果这些单元格是标题单元格(对于同一列或同一行中的其他单元格),对它们使用th元素并将第一行包装起来可能更合乎逻辑一个thead元素:

<table border="1">
    <thead>
        <tr>
            <th></th>
            <th>translate.com AND https://translate.google.com/</th>
            <th>http://www.bing.com/translator/</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>I eat tacos</th>
            <td>Yo como tacos</td>
            <td>Comer tacos</td>
        </tr>
    <!-- other rows here -->
    </tbody>
</table>

th元素默认以粗体显示(尽管您仍然可以使用CSS来明确说明)。它们也将默认居中;如果您不想这样,您可以轻松地使用CSS覆盖它,例如th { text-align: left }

在这种情况下,第一行看起来非常像标题行,因此我会将其设为thead th。这可能是有用的,例如因为如果页面被打印并且表格被分成两页或更多页面,那么许多浏览器会在新页面的开头重复该行。至于每行的第一个单元格,如果需要,它们最好保持为td并且只是粗体样式。

答案 1 :(得分:5)

CSS选择器:

tr:first-child td,
tr td:first-child {
    font-weight: bold;
}

说明:

:first-child用于选择一组元素的第一个子元素。例如:

<ul>
    <li>First</li>
    <li>Second/li>
    <li>Third</li>
    <li>Fourth</li>
</li>

li:first-child {}将涵盖第一个<li>

为了实现你的要求,我做了两件事,因为一个表是一组行。

  1. tr:first-child td(第一个表格行,所有td&#39; s)
  2. tr td:first-child(所有行,首先是td)
  3. 注意:规则#1和#2都将覆盖第一行,第一行td;但这应该不是问题。