Is it possible to adjust background image opacity in a xaringan slideshow?

1.8k views Asked by At

Is it possible to adjust the opacity of a background image when creating a presentation with xaringan and R markdown? For example, here is the Ninja template with just the slide of Karl for a background. What would I need to do to change the opacity of just this background?

Edit: Just to clarify, I would like to be able to adjust the background opacity on a case by case basis, not for every background image in the slideshow.

---
title: "Presentation Ninja"
subtitle: "⚔<br/>with xaringan"
author: "Yihui Xie"
institute: "RStudio, PBC"
date: "2016/12/12 (updated: `r Sys.Date()`)"
output:
  xaringan::moon_reader:
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---


background-image: url(`r xaringan:::karl`)
background-position: 50% 50%
class: right, top

# You only live once!
1

There are 1 answers

4
Martin C. Arnold On BEST ANSWER

You need to adjust the opacity of the parent element (a <div>) that contains the image using CSS. It's convenient to simply include a code chunk defining a CSS class that adjusts the opacity, e.g.,

```{css, echo = F}
.reduced_opacity {
  opacity: 0.5;
}
```

and then apply this class to the slide:

---
background-image: url(`r xaringan:::karl`)
background-position: 50% 50%
class: right, top, reduced_opacity
# You only live once!

However, this will reduce the opacity of the whole slide since everything on the slide 'lives' in this <div>. To avoid this, you could include the image with a class that adds a pseudo-element (using ::before) to the slide and adjust the opacity like this

```{css, echo = F}
.bg_karl {
  position: relative;
  z-index: 1;
}

.bg_karl::before {    
      content: "";
      background-image: url('https://github.com/yihui/xaringan/releases/download/v0.0.2/karl-moustache.jpg');
      background-size: cover;
      position: absolute;
      top: 0px;
      right: 0px;
      bottom: 0px;
      left: 0px;
      opacity: 0.5;
      z-index: -1;
}
```

and then add .bg_karl to the slide:

---
class: right, top, bg_karl
# You only live once!

enter image description here