Search code examples
htmlcsshtml-tablewidth

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


An unusual question that I haven't been able to locate the answer to:

Is it possible to overwrite tables styled with css, using the width attribute.

I would like html tables to default to a width of 100% (using css), unless a numeric width argument is passed to my table in the markup.

Right now, if I set the width of my table to auto in css, I am able to overwrite the width using the width attribute, by applying it to the table element in the markup. However, auto does not default to a width of 100%. If I set the width of my table to 100% in css, then I am unable to overwrite the width using the width attribute, by applying it to the table element in the markup.

Does anyone know of a work-around so that I may have my table-cake and eat it too?

.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>


Solution

  • 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>

    You can use :not selector. For example table:not([width]) Then css will be applied to all tables that haven't got width attribute