Wrap HTML Tables in Figures using Nanco and Kramdown

I noticed that on mobile phones, wide tables wouldn’t scroll horizontally – instead, they broke out of the content container and everything looked a bit wonky.

My goal: wrap <table> in <figure> and add figure { overflow-x: scroll; } to make the table scrollable inside its container.

Initially, I wanted to extend kramdown and, after the Markdown block element for tables have been added, wrap the whole thing in a <figure>. Maybe add a new block element to the representation of the Markdown document.

Even though kramdown is a very mature library, I couldn’t find an example for that, though. The next best thing I found was to add my own parser and then decorate the #parse function with a post-processing step.

I was way too lazy for that (my own website takes a while to compile so I would need a test project and then fiddle with the setup and interpret errors during compilation etc. etc.) – so instead I wrote a simple post-processor that takes the generated HTML and wraps any <table> tag in a <figure> tag using Nokogiri:

# lib/filters/wrap_table_in_figure.rb
class FigurizeTableFilter < Nanoc::Filter
  identifier :figurize_table

  def run(content, params={})
    return content unless content.include?("<table")
    doc = Nokogiri::HTML(html)

I exit early when no tables are present to avoid parsing the document for nothing.

The rest is a standard Nanoc Filter that I call for all my posts using filter :figurize_table in my Rules file.

Receive new .