首页 > 解决方案 > HTML 元素颜色、颜色和宽度 CSS 属性不起作用

问题描述

当我尝试在 HTML 中的 col 标记上应用不同的 CSS 属性以对一个表列具有不同的样式时,它不起作用。只有“背景颜色”有效。颜色、宽度、字体样式 CSS 属性不适用于列。

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
}

#col-1{

    background-color: blue;
    color: white;   
    width: 50px;
    font-style: italic;
}

</style>
</head>
<body>

<table>
  <colgroup>
    <col id="col-1">
    <col id="col-2">
    <col id="col-3">
  </colgroup>
  <tr>
    <th>ISBN</th>
    <th>Title</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>3476896</td>
    <td>My first HTML</td>
    <td>$53</td>
  </tr>
  <tr>
    <td>5869207</td>
    <td>My first CSS</td>
    <td>$49</td>
  </tr>
</table>

</body>
</html>

标签: htmlcsshtml-table

解决方案


只有border, background,widthvisibility应用于<col><column-group>元素https://www.w3.org/TR/CSS21/tables.html#columns

要更改第一列中的颜色,您需要一些针对每行的第一个子项的规则:

tr>th:first-child {
  color: white;
}
tr>td:first-child {
  color: white;
}

推荐阅读