You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用加载时CSS样式表内容异常显示的问题求助

Hey there! Sorry to hear you're hitting this odd glitch with your Shiny app—nothing ruins a holiday coding session like raw CSS popping up on your page. Let's break down what's likely going on and fix it up quick.

What's Causing This?

Most often, this happens because your CSS isn't being loaded correctly as a stylesheet. Either you've placed the includeCSS() call in a visible part of your UI (instead of the page's <head>), or you're using the wrong method to reference your external CSS file stored in www.

Fixes to Try

Here are the most reliable solutions:

  • Move includeCSS to the <head> section
    If you put includeCSS() inside a mainPanel() or other visible UI element, Shiny will render the raw CSS code as plain text. Wrap it in tags$head() so it's embedded properly as a stylesheet:

    ui <- fluidPage(
      tags$head(
        includeCSS("www/your-style.css")  # Double-check this path matches your file location
      ),
      # Rest of your UI elements (h1, p, etc.)
    )
    
  • Use tags$link instead (recommended for external files)
    Since your CSS lives in the www directory (Shiny's default static asset folder), using tags$link is more seamless. Shiny automatically serves files from www, so you don't need to add the www/ prefix:

    ui <- fluidPage(
      tags$head(
        tags$link(rel = "stylesheet", type = "text/css", href = "your-style.css")
      ),
      h1("Your Custom Heading"),
      p("Some styled paragraph text")
    )
    
  • Verify your file setup
    Make sure your CSS file is exactly in the www folder (no typos in the folder name), and that the filename in your code matches the actual file (watch for capitalization—this matters on macOS/Linux!).

  • Clear cache & restart
    Sometimes old browser cache or a stuck R session causes weird behavior. Restart your R session, close and reopen your browser, or do a hard refresh (Ctrl+Shift+R on Windows/Linux, Cmd+Shift+R on Mac) to rule this out.

Example Corrected UI

Here's how your full UI might look with the recommended tags$link approach:

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "custom-style.css")
  ),
  h1("Hello Shiny with Custom Styles"),
  h3("Subheading Example"),
  p("This paragraph should follow your custom font and line-height rules.")
)

That should get your styles working without the raw CSS popping up. Happy holidays, hope this gets your app running smoothly!

内容的提问来源于stack exchange,提问作者lupo404

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:00:44