使用html width属性覆盖在css中声明的表格宽度

问题描述 投票:0回答:1

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.