Since the question is about styling an html_document
, you have to use some CSS
rules. There are many means to obtain the desired formatting.
In order to find a set of CSS
rules that achieve your goal, it is necessary to inspect the rendered HTML
document. Here's the relevant HTML
fragment of the default R Markdown
document provided in the question:
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Here is the title</h1>
</div>
<div id="r-markdown" class="section level2">
<h2>R Markdown</h2>
<p>FIRST PARAGRAPH This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <a href="http://rmarkdown.rstudio.com" class="uri">http://rmarkdown.rstudio.com</a>.</p>
<p>SECOND PARAGRAPH you click the <strong>Knit</strong> button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:</p>
</div>
Here is one solution that uses the margin
property and the :first-of-type
pseudo-class:
---
title: "Here is the title"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{css echo=FALSE}
/* Define a margin before h2 element */
h2 {
margin-top: 6em;
}
/* Define a margin after every first p elements */
p:first-of-type {
margin-bottom: 3em;
}
```
## R Markdown
FIRST PARAGRAPH This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
SECOND PARAGRAPH you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
If you use these CSS
rules in your final document, you may be disappointed because you'll get a space before each h2
element and after each first p
element. So, you may prefer selecting elements with the div
identifier:
```{css echo=FALSE}
#r-markdown {
margin-top: 6em;
}
#r-markdown p:first-of-type {
margin-bottom: 3em;
}
```