使用xaringan::moon_reader制作R Markdown演示文稿时CSS背景颜色不生效的问题求助
Great question! Let's figure out why your background color isn't showing up and fix it step by step.
First, let's start with a tiny syntax fix in your YAML header—your output line isn't formatted correctly for R Markdown. Proper indentation matters here, so it should look like this:
--- title: "Changing CSS" output: xaringan::moon_reader: nature: default # You can omit this line if you just want the default settings ---
Now, onto the main issue: Your body { background-color: blue; } rule isn't working because xaringan's slide structure uses a .slides container (that wraps all your slides) and individual .slide elements. These elements have their own background styles that take priority over the body's background, so your body setting gets hidden.
Here are two simple fixes to get that blue background showing up:
Fix 1: Set a global background for all slides
Update your CSS chunk to target the .slides container instead of just the body. This will apply the blue background to every slide in your presentation:
```{css, echo = FALSE} body { color: red; /* This still works perfectly for text color */ } .slides { background-color: blue; /* This will override the default slide background */ }
### Fix 2: Style individual slides If you'd rather set the background per-slide (maybe you want different backgrounds later), target the `.slide` class instead: ```css ```{css, echo = FALSE} body { color: red; } .slide { background-color: blue; /* Applies to each individual slide */ }
### Bonus: Set a background for just one slide If you only want a single slide to have the blue background, you can add an inline style directly to that slide's section: ```markdown --- # Hello 2 <style> .this-slide { background-color: blue; } </style> Another Content ---
Or use a custom class for the slide and define it in your CSS:
--- class: blue-bg # Hello 2 Another Content --- /* Add this to your CSS chunk */ .blue-bg { background-color: blue; }
That should resolve the issue! The key was understanding that xaringan's slide hierarchy has its own background styles that override the body's settings.
内容的提问来源于stack exchange,提问作者CharlotteS.

