# Streamlit Layout: Columns, Tabs, Sidebar, and Containers

> How to lay out a Streamlit app: st.sidebar, st.columns with custom widths and vertical alignment, st.tabs, st.expander, st.popover, horizontal containers, and the wide page setting.

Source: https://www.pythoncharts.com/streamlit/streamlit-layout/ | Published: 2026-11-26 | Author: Alex Scott | Category: Streamlit | Tags: streamlit, st.columns, st.tabs, st.sidebar, layout

Use `st.sidebar` for controls, `st.columns` to put elements side by side, `st.tabs` to stack views in the same space, and `st.expander` to hide detail until someone asks for it. Each one returns a container that you write into with a `with` block. The code here was tested with Streamlit 1.67.

## Quick Example

Save this as `app.py` and run `streamlit run app.py`. It lays out a month of simulated readings from a home solar system.

```python
import numpy as np
import pandas as pd
import streamlit as st

st.set_page_config(page_title="Solar Monitor", layout="wide")

rng = np.random.default_rng(12)
days = pd.date_range("2026-06-01", periods=30)
solar = rng.normal(24, 5, 30).clip(8).round(1)
home = rng.normal(17, 3, 30).clip(8).round(1)
df = pd.DataFrame({"day": days, "Solar": solar, "Home use": home})

with st.sidebar:
    st.header("Settings")
    window = st.slider("Smoothing (days)", 1, 7, 3)
    price = st.number_input("Price per kWh ($)", 0.0, 1.0, 0.18, 0.01)

st.title("Solar Monitor")

surplus = df["Solar"].sum() - df["Home use"].sum()
left, middle, right = st.columns(3, border=True)
left.metric("Generated", f"{df['Solar'].sum():,.0f} kWh")
middle.metric("Used", f"{df['Home use'].sum():,.0f} kWh")
right.metric("Surplus value", f"${surplus * price:,.2f}")

chart_tab, data_tab = st.tabs(["Chart", "Data"])
smoothed = df.set_index("day").rolling(window, min_periods=1).mean()
chart_tab.line_chart(smoothed, color=["#e8590c", "#5f3dc4"], y_label="kWh")
data_tab.dataframe(df, hide_index=True)

with st.expander("How is surplus value calculated?"):
    st.write("Generation minus home use, multiplied by the price per kWh.")
```

![Streamlit app with a settings sidebar, three bordered metric columns, Chart and Data tabs, a line chart and a collapsed expander](https://www.pythoncharts.com/streamlit/streamlit-layout/images/streamlit-layout.png)

The same `st.` calls work on a container object (`left.metric(...)`) or inside `with left:`. Use the `with` form when several elements go in one place.

## Which Streamlit Layout Element Should You Use?

| Element | What it does | Use it for |
|---|---|---|
| `st.sidebar` | Collapsible panel on the left | Settings that apply to the whole page |
| `st.columns` | Side-by-side containers | Metrics, charts to compare |
| `st.tabs` | Views stacked in one space | Chart and data versions of the same thing |
| `st.expander` | Section that opens on click | Explanations and advanced options |
| `st.popover` | Button that opens a floating panel | A few filters without taking up space |
| `st.container` | Grouping box, optionally horizontal | Borders, button rows, fixed-height scrolling |
| `st.empty` | Slot holding one element | Replacing content in place |

## Set Column Widths, Gaps, and Alignment

Pass a list to `st.columns` for relative widths. `[3, 1]` makes the first column three times as wide as the second. `gap` sets the space between them (`"small"` is the default), and `vertical_alignment="bottom"` lines up a button with the input next to it:

```python
import streamlit as st

search_col, button_col = st.columns([4, 1], vertical_alignment="bottom")
query = search_col.text_input("Search readings", placeholder="2026-06-14")
button_col.button("Search", width="stretch")

main, side = st.columns([2, 1], gap="large", border=True)
with main:
    st.subheader("Main panel")
    st.write("Two thirds of the width.")
with side:
    st.subheader("Side panel")
    st.write("One third of the width.")

phone = st.columns(4, wrap=False)
for col, label in zip(phone, ["Mon", "Tue", "Wed", "Thu"]):
    col.button(label, width="stretch")
```

![A search box aligned with its button, two bordered columns in a two to one ratio, and a row of four buttons](https://www.pythoncharts.com/streamlit/streamlit-layout/images/streamlit-layout-columns.png)

On screens 640 pixels wide or narrower, columns stack vertically. `wrap=False` keeps them in one row, which suits short items such as buttons. Streamlit recommends nesting columns no more than once.

## Put Buttons in a Row With a Horizontal Container

For a toolbar, `st.container(horizontal=True)` is simpler than columns. Each element keeps its natural width and wraps to the next line when space runs out:

```python
import streamlit as st

with st.container(horizontal=True, horizontal_alignment="right"):
    st.button("Reset")
    with st.popover("Filters"):
        st.checkbox("Weekends only")
        st.slider("Minimum output (kWh)", 0, 40, 10)
    st.button("Export", type="primary")

with st.container(height=140, border=True):
    for day in range(1, 31):
        st.write(f"June {day}: panels online")
```

![Reset, Filters and Export buttons aligned to the right, above a bordered box with a scrolling list of days](https://www.pythoncharts.com/streamlit/streamlit-layout/images/streamlit-layout-containers.png)

The second container has a fixed `height`, so its 30 lines scroll inside the box.

## Do Hidden Tabs Still Run?

Yes. By default, Streamlit runs the code for every tab and expander, whether or not it's visible. If one tab is slow, add `on_change="rerun"` and check the tab's `.open` property:

```python
import time

import streamlit as st

summary, report = st.tabs(["Summary", "Full report"], on_change="rerun")

with summary:
    st.write("Loads right away.")

if report.open:
    with report:
        with st.spinner("Building the report..."):
            time.sleep(2)
        st.write("Built only when this tab is selected.")
```

With `on_change="rerun"`, switching tabs reruns the script. `st.expander` and `st.popover` accept the same argument. You can also move expensive work behind [`@st.cache_data`](https://www.pythoncharts.com/streamlit/streamlit-caching/) so it only runs once.

## Replace Content in Place With st.empty

`st.empty()` reserves one slot. Each write replaces what was there, which works for status messages:

```python
import time

import streamlit as st

status = st.empty()
for step in ["Reading meter", "Summing totals", "Done"]:
    status.info(step)
    time.sleep(0.5)
```

## Practical Tips

- **Call `st.set_page_config(layout="wide")` for dashboards.** The default centered layout is narrow for three or more columns.
- **Keep the main content out of the sidebar.** On phones the sidebar starts collapsed, so put only controls there. `initial_sidebar_state="collapsed"` collapses it everywhere.
- **Write into containers out of order.** Create a container at the top of the page, then fill it after the calculations further down.
- **Spread a large app across pages** with [`st.navigation`](https://www.pythoncharts.com/streamlit/streamlit-multipage-app/) instead of adding more tabs.

## Similar Topics

- [Streamlit Tutorials: A Guide from First App to Deployment](https://www.pythoncharts.com/streamlit/streamlit-python-guide/)
- [How to Build a Multipage App in Streamlit](https://www.pythoncharts.com/streamlit/streamlit-multipage-app/)
- [How to Build a KPI Dashboard in Streamlit](https://www.pythoncharts.com/streamlit/streamlit-kpi-dashboard/)
