如何让Shiny应用中div的内容适配屏幕宽度?
如何让Shiny应用中div的内容适配屏幕宽度?
嘿,我看了你这个Shiny应用里的div适配问题,咱们来一步步搞定它~
首先看你代码里的小问题:你虽然给div加了width: 100%;,但外面套的splitLayout默认带了布局限制,导致内容没法真正跟着屏幕走;而且如果没处理好盒模型,内边距这类元素还可能让内容溢出屏幕。
给你两个解决方案,按需选:
方案1:移除不必要的splitLayout(单内容列推荐)
如果你的splitLayout里只有这一个div,那完全可以去掉它,直接用div承载内容,布局会更灵活:
library(shiny) ui <- fluidPage( uiOutput("preview") ) server <- function(input, output, session) { deployExeList <- function(){ return( shiny::div( class = "", style = "width: 100%; padding: 0 15px; box-sizing: border-box;", shiny::withMathJax( shiny::HTML( markdown::markdownToHTML( text = "### **aaa/bbbb: ccc000.**\n### In recent years, automatic analyses using novel NLP methods have been used to investigate language abnormalities in schizophrenia. In contrast, only a few studies used automated language analyses in bipolar disorder. To our knowledge, no previous research compared automated language characteristics of first-episode psychosis (FEP) and bipolar disorder (FEBD) using NLP methods", fragment.only = TRUE ) ) ) ) ) } output$preview <- renderUI({ deployExeList() }) } shinyApp(ui, server)
这里的关键修改:
- 删掉了
splitLayout,避免它带来的多余布局限制 - 给div加了
box-sizing: border-box;:这个属性能让div的内边距、边框算在100%宽度里,不会导致内容溢出 - 加了
padding: 0 15px;:让内容不要紧贴屏幕边缘,看着更舒服,你可以根据需求调整这个值
方案2:保留splitLayout(多内容列需要时用)
如果确实需要用splitLayout放多列内容,那给它加上cellWidths = "100%"参数,确保单元格占满父容器:
library(shiny) ui <- fluidPage( uiOutput("preview") ) server <- function(input, output, session) { deployExeList <- function(){ return( splitLayout( id=paste0("slexe"), cellWidths = "100%", # 让splitLayout单元格占满宽度 shiny::div( class = "", style = "width: 100%; box-sizing: border-box;", shiny::withMathJax( shiny::HTML( markdown::markdownToHTML( text = "### **aaa/bbbb: ccc000.**\n### In recent years, automatic analyses using novel NLP methods have been used to investigate language abnormalities in schizophrenia. In contrast, only a few studies used automated language analyses in bipolar disorder. To our knowledge, no previous research compared automated language characteristics of first-episode psychosis (FEP) and bipolar disorder (FEBD) using NLP methods", fragment.only = TRUE ) ) ) ) ) ) } output$preview <- renderUI({ deployExeList() }) } shinyApp(ui, server)
这样修改后,splitLayout的单元格会占满整个屏幕宽度,里面的div也会跟着适配,内容自然就不会溢出了。
总的来说,核心就是让容器宽度设置正确,并用box-sizing处理好盒模型——markdown渲染的内容本身会自动换行,只要容器适配屏幕,内容就会跟着适配啦~
备注:内容来源于stack exchange,提问作者Lev




