使用 html 宽度属性覆盖 css 中声明的 table 宽度

Overwriting table width declared in css, with the html width attribute

一个我无法找到答案的不寻常问题:

是否可以使用 width 属性覆盖带有 css 样式的 tables。

我希望 html table 默认为 100%width(使用 css),除非数字 width 参数在标记中传递给我的 table。

现在,如果我将 table 的 width 设置为 css 中的 auto,我可以使用 width 覆盖宽度] 属性,方法是将其应用于标记中的 table 元素。但是,auto 不会默认为 100% 的宽度。如果我将 table 的 width 设置为 css 中的 100%,那么我无法使用 width 属性覆盖宽度,方法是将其应用于标记中的 table 元素。

有谁知道有什么变通方法可以让我吃 table-蛋糕并吃掉它吗?

.table-a {
  width: 100%;
  border: 1px solid black;
  margin: 48px auto 16px;
}

.table-b {
  width: auto%;
  border: 1px solid black;
  margin: 48px auto 16px;
}
<table class="table-a" width="200">
  <tr>
    <td>Foo</td>
    <td>Bar</td>
  </tr>
</table>

<table class="table-b" width="200">
  <tr>
    <td>Foo</td>
    <td>Bar</td>
  </tr>
</table>

<table class="table-b">
  <tr>
    <td>Foo</td>
    <td>Bar</td>
  </tr>
</table>

<p>Table A seems to show that the width attribute will not override external stylesheets the same way inline stylesheets.</p>

<p>Is there a way to ensure that when a width attribute is not passed to a table, that it defaults to 100%, and otherwise adheres to the width declaration/</p>

table {
  border: 1px solid black;
  margin: 48px auto 16px;
}

table:not([width]) {
  width: 100%;
}
<table width="200">
  <tr>
    <td>Foo</td>
    <td>Bar</td>
  </tr>
</table>

<table>
  <tr>
    <td>Foo</td>
    <td>Bar</td>
  </tr>
</table>

<p>The :not() selector successfully enables me to use the width attribute in the markup and style every other table with a width of 100%.</p>

您可以使用 :not 选择器。例如table:not([width]) 然后 css 将应用于所有没有 width 属性的表