Home > Enterprise >  Set width to 100% (fill container) with pandas set_table_styles
Set width to 100% (fill container) with pandas set_table_styles

Time:10-13

Context: I have the following dataframe that I'm applying several stylying steps to then transform into HTML and display it in a web page.

The dataframe and styles being applied:

th_props = [
  ('font-size', '14px'),
  ('text-align', 'left'),
  ('font-weight', 'bold'),
  ('color', '#6d6d6d'),
  ('background-color', '#eeeeef'),
  ('border','1px solid #eeeeef'),
  #('padding','12px 35px')
]

td_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
  #('width','100%')

]

cell_hover_props = [  # for row hover use <tr> instead of <td>
    ('background-color', '#eeeeef')
]

headers_props = [
    ('text-align','center'),
    ('font-size','1em')
]
#dict(selector='th:not(.index_name)',props=headers_props)

table_props = [
    ('width','100%')
]
#dict(selector='table',props=table_props),


styles = [
    dict(selector="th", props=th_props),
    dict(selector="td", props=td_props),
    dict(selector="td:hover",props=cell_hover_props),
    # dict(selector='th.col_heading',props=headers_props),
    dict(selector='th.col_heading.level0',props=headers_props),
    dict(selector='th.col_heading.level1',props=td_props),

]


    arrays = [
        ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
        ["one", "two", "one", "two", "one", "two", "one", "two"],
    ]
    tuples = list(zip(*arrays))
    
    index = pd.MultiIndex.from_tuples(tuples, names=[None, "Brand"])
    
    df = pd.DataFrame(np.random.randn(3, 8), index=["A", "B", "C"], columns=index)

st.markdown(df.style.set_table_styles(styles).to_html(),unsafe_allow_html=True)

Which gives me this dataframe when rendered to a webpage: enter image description here

As you can see, the table doesn't extend thourgh the whole container. How can I set the width of the table to 100%?

Attempts:

I've tried editting the th_props and td_props adding ('width','100%') as such:

td_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
  ('width','100%')

But I get things like this:

enter image description here

Which selector and property should I use in set_table_styles in pandas to get something like this:

enter image description here

Thank you!

CodePudding user response:

Try changing 100% to 100vw in table_props And if that causes some issues such as overflow you can do something like 95vw or something as well.

1 more thing you can try if its still a little weird is change 100vw back to 100% in table_props and then try adding 100vw to the width in td_props and that might solve your issue as well.

  • Related