3MW (Aligning elements in Shiny apps - Final Part)

Guten Tag!

Many greetings from Ulm, Germany.

Before we jump into this week’s issue, let me remind you that I’m giving a talk for the R User Group at the Harvard Data Science Initiative on May 18. You can sign up and join us for free online.

Now, let us do a quick recap from last week. We were in the midst of building this habit tracker app with Shiny.

Our goal was to learn how to align content with HTML and CSS. Last time, we stopped after centering the name of the habit.

In this code, we used only divs, checkboxes and a little bit of CSS.

Now, it’s time to finish this app. Let us align the checkboxes properly as well and add more habits. As always, the full code can be found on GitHub. (ADD LINK)

Find and target CSS classes

We created this app using flexboxes by setting margin-top and margin-bottom to auto. We can do the same thing to align the checkboxes properly. But this requires inserting CSS into the right places.

The problem is that Shiny generates the HTML code using custom CSS classes for us. Thus, we have to overwrite the CSS that Shiny uses internally. We do this by inserting our own style for the corresponding CSS classes into our app. As is often the case, the trick is to find the correct class name that we need to target. This can only be done by strolling through the HTML code of the app with your web browser.

And it gets worse. The checkboxes are nested into other containers that Shiny creates. And these containers have classes of their own. This means that we have to find multiple class names to

  1. enable flexbox display in the surrounding divs (in order to enable auto-margins)

  2. change widths, height and margin of the checkbox (width and height optional but looks better)

Once we've found these class names we can insert their new CSS code with tags$style().

Excellent! This code will center our checkboxes. The app is already starting to look great.

Scale the app

Now, let us wrap our code it into a Shiny module. This way, we can scale our app to track more than just one habit without having to copy and paste code. You know, because copy-and-pasting is really bad. Especially in Shiny. (If you're not familiar with modules yet, no worries, I’ve got you covered.)

And once we have refactored the code logic into modules we can easily add more habits.

Add day labels

Finally, we just have to add the numbers 1 to 31 on top of the habit rows. For horizontally aligning the numbers, we can wrap the them into a div of the same width as the checkboxes and set text-align:center; 

Congrats, we have finished our app. Hope you’ve enjoyed this week’s newsletter. If you want to reach out to me, just reply to this mail or find me on Twitter.

See you next week!
Albert 👋

If you like my content, you may also enjoy these:

Reply

or to participate.