Joel Joel - 1 year ago 377
R Question

Adding background image to Shiny NavBarPage

I'm trying to add a background image to a Shiny App. I need it fixed into the top left corner. So far the background image is not loading. The color is loading and the font appears to be fine. Just no image.

This is my CSS:

body {
background-image: url("header.png");
background-position: left top;
background : #000000;

and here is where I'm including it in my Shiny:

ui = navbarPage(

Thanks in advance for the help.

Answer Source

If you want to add an image (or customize anything really in a shiny layout) there are two ways to do it. The first is just to write your own html via the tags object, which contains all the functions you need to reproduce a page

The other, (and frankly easier way), is to just make a small modification to the existing functions. On the ui side, shiny tags are just lists, and you can access, add, or replace whatever additional tags you like inside of them.

To start, you need to save the resulting shiny object

so, instead of:


navbarPage(title = 'test')

we do it this way:


FullPage <- navbarPage(title = 'test')

once you have that FullPage object, you can modify whatever you want. Each level is either a list of shiny tag objects, or a shiny tag object itself.

a shiny tag object has three slots,

  • name (if the tag is for an img, this would be 'img')
  • attribs (this could be a class for css, or src for img, or any new attributes you may create)
  • children (any tags nested inside this tag)

so, in order to add an image in the top left, where the title currently is in a navbar page, I would do the following:


FullPage <- navbarPage('test')
FullPage[[3]][[1]]$children[[1]]$children[[1]]$children[[1]] <- 
                    tags$img(src = 'logo.png', width = 60, height = 60)

what's being done here?

Well, the navbarPage generates a list with 3 shiny objects,

the first 2 contain (I believe) the head, the third contains the body of the page.

That itself is a list of shiny objects, The first one contains the title section. In turn, the first child of the first child is the title tags, so we replace that with a tags$img object. We could have replaced that with anything.

Such as tags$a(href = 'http://mynewlinklocation', tags$img(src = 'logo.png')) for a clickable image.

With any other custom modifications to your page, I recommend playing around with the object in the console.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download