首页 > 解决方案 > 用 html width 属性覆盖在 css 中声明的表格宽度

问题描述

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

是否可以使用该width属性覆盖使用 css 样式的表格。

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

现在,如果我在 css 中将width表格设置为auto,我可以使用width属性覆盖宽度,方法是将其应用于table标记中的元素。但是,auto不默认为100%. 如果我将width表格的 设置为100%css 中的,那么我无法使用width属性覆盖宽度,方法是将其应用于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>

标签: htmlcsshtml-tablewidth

解决方案


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属性的表


推荐阅读