How to avoid page breaks right after or in the middle of section titles in a EPUB book created with Bookdown?
12:34 25 Feb 2026

I created an EPUB ebook in R with Bookdown but I am struggling with making sure that section titles do not get spread across different pages. For each section title I want to make sure that the entire title stays together on the same page, and does not get split between the end of one page and the beginning of the following page on the device. I tampered with my style.css file and with the _output.yml file but to be honest I don't know what I am doing, I don't know YAML or CSS.

This is my style.css:

p.caption {
  color: #777;
  margin-top: 10px;
}
p code {
  white-space: inherit;
}
pre {
  word-break: normal;
  word-wrap: normal;
}
pre code {
  white-space: inherit;
}
h1, h2, h3, h4 {
  page-break-after: avoid;
  break-after: avoid;
}
page-break-inside: avoid;

The last few lines should be the ones making sure that there isn't a page break inside or right after a title.

This is my _output.yml:

bookdown::pdf_book:
  css: style.css
  config:
    toc:
      before: |
        
  • My book title
  • after: |
  • Impaginato con bookdown
  • bookdown::epub_book: stylesheet: style.css

    This is the preamble in my index.Rmd file:

    --- 
    title: My title
      
    subtitle: My subtitle
    
    author: "Me"
    toc-title: Indice
    toc: false
    output: pdf_book
    header-includes:
      - \usepackage{graphicx}
      - \usepackage{float}
      - \usepackage{boxhandler}
      - \captionStyle{n}{l}
      - \usepackage[twoside]{fancyhdr}
      - \pagestyle{fancy}
      - \fancyhead{}
      - \renewcommand{\headrule}{}
      - \fancyfoot[L]{My book title}
      - \fancyfoot[R]{\copyright Me}
    ---
    

    This is the code I am executing in R to produce the EPUB file:

    bookdown::render_book(input="index.Rmd", 
        bookdown::epub_book(fig_width = 5, fig_height = 4, 
            dev = "png", fig_caption = TRUE, 
            number_sections = TRUE, 
            toc = FALSE, toc_depth = 2, 
            stylesheet = NULL,
            metadata = NULL, 
            chapter_level = 1, 
            epub_version = c("epub3", "epub", "epub2"), 
            md_extensions = NULL,
            pandoc_args = NULL, 
            template = "default"
            )
        )
    

    It works but it is not making sure to avoid page breaks inside or right after a title. May anyone help me fix this? Thank you in advance.

    css r r-markdown bookdown