user2748320 user2748320 - 1 year ago 131
HTML Question

r knitr kable padding not working with format = "html"

I am trying to add padding to a table I am creating in an RMarkdown file that will generate both a pdf and an html flexdashboard. I know that there are a number of functions/packages I could use (pander, xtable, DT, etc.), but I would prefer to use the kable function from the knitr package.

The trouble I am having is that the padding argument does not seem to work. I would appreciate any help in solving this without having to add custom CSS to my document.

As a example, I have tried to run the code with padding set to 0, 10, 20 but the tables all look identical in the html file.

knitr::kable(head(cars), format = "html", padding = 0)
knitr::kable(head(cars), format = "html", padding = 10)
knitr::kable(head(cars), format = "html", padding = 20)

enter image description here

I am using knitr_1.14 and rmarkdown_1.0, and my session information is as follows.

R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Answer Source

The option table.attr='cellpadding="20px"' does not work for me. Using CSS styles and adding a class to the table with table.attr='class="myTable"' leads to all tables having the desired padding property (even if only one table carries the new class).

If I only want to modify one single table I usually go with jQuery:

title: "Table Cell Padding"
output: html_document

knitr::kable(head(cars), format = "html")
knitr::kable(head(cars), format = "html", table.attr='class="myTable"')
  .myTable td {
    padding: 40px;

enter image description here

Another option is to use jQuery to edit individual elements. The following example modifies the table in the same way as the CSS styles above.

<script type="text/javascript">
  // When the document is fully loaded...
  $(document).ready(function() {
    // ... select the cells of the table that has the class 'myTable'
    // and add the attribute 'padding' with value '20px' to each cell
    $('table.myTable td').css('padding','20px');

Here I add the class myTable to the table I want to modify. Afterwards I execute some JavaScript (see comments). You could add any other CSS property to the table elements (or the table itself $('table.myTable').css(...)) in the same way (e.g. $('table.myTable td').css('background-color','red');)