How to Override Default CSS in R Markdown HTML Documents
When rendering an HTML document from an R Markdown (.Rmd) file, the default styling is powered by a built-in Bootstrap template. This template wraps all rendered content inside a <div class="container-fluid main-container">, restricting the content to a default max-width: 940px.
If you have linked a custom stylesheet using the css: "own.css" YAML option, you might find that your attempts to adjust .main-container are ignored in the browser. This happens because default styles either load later in the cascade or conflict with Bootstrap's selector priority. Here are the best ways to ensure your custom CSS rules take precedence.
Solution 1: Increase CSS Specificity (Recommended)
Rather than fighting the CSS cascade order, the cleanest approach is to make your CSS selector more specific than the default template selector. In your own.css file, chain the classes or add an element tag:
/* Target both classes together */
div.container-fluid.main-container {
max-width: 80%;
margin-left: auto;
margin-right: auto;
}
/* Or qualify with the body tag */
body .main-container {
max-width: 80%;
}Because div.container-fluid.main-container has higher specificity than the default .main-container selector, the browser will prioritize your custom rule without requiring brute-force overrides.
Solution 2: Use the !important Flag
If you prefer a quick, foolproof solution that does not rely on tweaking selector specificity, append !important to the properties you want to enforce:
.main-container {
max-width: 80% !important;
}This overrides any previously declared rules regardless of when or where the default Bootstrap template loads.
Solution 3: Inject CSS Directly via an R Code Chunk
Another reliable way to guarantee that your styles load at the very bottom of the document (thereby winning cascade ties) is to include an inline css chunk inside your .Rmd document:
```{css, echo=FALSE}
.main-container {
max-width: 80%;
}
```This will insert a <style> tag directly into the generated HTML body, ensuring it runs after the header styles are evaluated.
Solution 4: Modern Approach with bslib
If you are using modern R Markdown versions, you can take advantage of the bslib package. Rather than hacking custom CSS for basic layout widths, configure Bootstrap variables directly within the YAML header:
---
title: "Custom Layout Document"
output:
html_document:
theme:
version: 5
container-max-width: "80%"
toc: false
number_sections: true
---Summary
The standard max-width: 940px constraint in R Markdown is embedded by default template styles. You can override it by using a more specific selector like div.container-fluid.main-container, adding !important to your CSS declaration, or using an inline ```{css}``` chunk.