JavaScript · · 2 min read

How to properly style a markdown table

This post shows you how to properly format a markdown table together with Metalsmith and marked.js

How to properly style a markdown table


While developing this my old blog using metalsmith in conjunction with metalsmith-markdown, I came across an issue, that didn't allow me to properly use markdown tables and style them accordingly.

Admittedly marked.js, which is used by the plugin, converted the following markdown...

| Tables        |      Are      |   Cool |
| ------------- | :-----------: | -----: |
| col 3 is      | right-aligned | \$1600 |
| col 2 is      |   centered    |   \$12 |
| zebra stripes |   are neat    |    \$1 |

...correctly into this:

      <th align="center">Are</th>
      <th align="right">Cool</th>
      <td>col 3 is</td>
      <td align="center">right-aligned</td>
      <td align="right">$1600</td>
      <td>col 2 is</td>
      <td align="center">centered</td>
      <td align="right">$12</td>
      <td>zebra stripes</td>
      <td align="center">are neat</td>
      <td align="right">$1</td>

So far so good. But how on earth am I now able to apply the bootstrap table selectors to it?


The solution was to use a custom renderer and override the block level method for table.

var metalsmith = require("metalsmith")
var markdown = require("metalsmith-markdown")
var marked = require("marked")
var markedRenderer = new marked.Renderer()

markedRenderer.table = function(header, body) {
  const replaced_header = header.replace(/<th/g, '<th scope="col"')
  var table = `
        <table class="table table-striped table-dark">

  return table

  // ...
      renderer: markedRenderer,
// ...

This allowed me to inject my custom classes and style it accordingly. Of course there are more block level methhods which you can override, have a look here: Marked.js Documentation