Search code examples
rr-markdownbookdown

In R bookdown how do I set the default code output background color


My R bookdown book with gitbook style renders with the code output in a gray box. I would like to change it to be a white box with a black border. I have found posts showing how to set the color for a specific block but not how to set the default. I think I need to add a css file like this:

--- 
title: x
author: clueless
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
output:
  bookdown::gitbook: 
    css: "style.css"
---

but I a don't know where to go from here. I know very little css. So clues for the clueless would be greatly appreciated.


Solution

  • Using only CSS

    The previous answer is correct for the CSS rule but the selector must be more specific for a gitbook() format. This a matter of CSS specificity.

    Using a browser inspector, you can get a sense of the selector you need to use to override default CSS style set by gitbook.

    This simple css will replace background and add a border

    .book .book-body .page-wrapper .page-inner section.normal pre {
        background: #fff;
        border: 1px solid #ddd;
        border-color: #000;
    }
    

    You put in as you do in style.css and use the css argument of bookdown::gitbook in index.Rmd or in _output.ymldepending of which you are using.

    This will pick up the CSS.

    I think you could also use !important to have the most specify on pre with

    pre {
        background: #fff !important;
        border: 1px solid #ddd !important;
        border-color: #000 !important;
    }
    

    (Edit after comment above)

    Using knitr feature

    Another way would be to use class.source and class.output https://bookdown.org/yihui/rmarkdown-cookbook/chunk-styling.html

    This would allow you to set a specific class for your output and target this class in your CSS.

    it would require to apply the chunk option to all code chunk using

    knitr::opts_chunk$set(class.output = "custom-output")
    

    Then you could use pre.custom-output to target only the code chunk output part, using one of the two syntax above (full selectors or !important)