How to add a default CSS class for one kind of elements in Hugo?

1k Views Asked by At

I'm modifying a theme I found for Hugo and I wondered how I can add a css class to the tables in the HTML code generated. I want to use a css framework and I would like if the tables haveclass="u-full-width", I know I can edit the css codes but I think there must be a clever way.

Somthing that automatically add the class attributes to every tables in the HTML generated code.

2

There are 2 best solutions below

8
On

You can do that with javascript you can simply use var tables = document.getElementsByTagName("table") as your selector.

Then add the class using for

here is the code

window.onload = function() {
    var tables = document.getElementsByTagName("table"),
        len = tables !== null ? tables.length : 0,
        i = 0;
    for(i; i < len; i++) {
        tables[i].className += " u-full-width"; 
    }
}
function addclass(){
    var tables = document.getElementsByTagName("table"),
        len = tables !== null ? tables.length : 0,
        i = 0;
    for(i; i < len; i++) {
        tables[i].className += " u-not-full-width"; 
    }
}
table {
border:1px solid #000;
width:100%;
height:300px;
}
td {
border:1px solid red;
}
.u-full-width{
background-color:blue;
}
.u-not-full-width{
background-color:green !important;
}
<button onclick="addclass();">Add class to all tables</button>
<table>
 <tbody>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
 </tbody>
</table>
<table >
 <tbody>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
 </tbody>
</table>
<table >
 <tbody>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
  <tr>
   <td> </td>
   <td> </td>
   <td> </td>
  </tr>
 </tbody>
</table>

Yes you can

0
On

After doing a little digging, I assume you're using the SKELETON CSS Framework?

I think your best option here is to wrap your tables with vanilla markup, and add a single line of CSS:

<div class="u-full-width">
| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |
</div>

... with your CSS like so:

div.u-full-width > table {
  width: 100%;
  box-sizing: border-box;
}

... or alternatively, you can inherit the styles from SKELETON:

div.u-full-width > table {
  width: inherit;
  box-sizing: inherit;
}