itsMeInMiami
itsMeInMiami

Reputation: 2783

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.

Upvotes: 2

Views: 671

Answers (2)

cderv
cderv

Reputation: 6552

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)

Upvotes: 2

Aman
Aman

Reputation: 417

Your code snippets are styled with the <pre> tag. If you've figured out how to link your CSS file, adding the below to it should give you the results you want:

For example:

pre {
    background: #fff;
    border: 1px solid #ddd;
    border-color: #000;
    page-break-inside: avoid;
    font-family: monospace;
    font-size: 15px;
    line-height: 1.6;
    margin-bottom: 1.6em;
    max-width: 100%;
    overflow: auto;
    padding: 1em 1.5em;
    display: block;
    word-wrap: break-word;
}
<body>
<pre> 
Hello this is code 
This is more code. 
You could have this could be whatever you want.
Monty Python!
</pre>

</body>

Feel free to tweak the numbers and values to fit your need.

Upvotes: 1

Related Questions