MonterUI Page Layout Guide
This guide will discuss 3 tools for laying out your app pages, Grid, Flexbox, and Columns. This page will discuss the strengths and when to use each individually, and then a section for how to combine them for more complex layouts at the end.
Note: This guide is designed to get you started building layouts quickly, not to teach you all the details needed to build every possible custom layout with pixel-perfect control. To get more detailed and lower-level control, explore the tailwind docs.
This guide is for creating flexible layouts you envision, but does not discuss responsiveness to make different layouts that are both mobile and desktop friendly. Stay tunes for a responsiveness guide that will help with that!
Grid
Grids are best for regular predictable layouts with lots of the same shape of things that may need to change a lot for different screen sizes. I think the best way to see what it can do is to see a bunch of examples, so here they are!
Minimal Image Cards
This is a minimal example of a grid that just shows image and text. This is the foundation for many more complex layouts so make sure to understand what's going on here first before moving on!
A grid lays things out in a...grid. As you can see, we have evenly sized cards by default.
Image 0
Image 1
Image 2
Image 3
Image 4
Image 5
def picsum_img(seed): return Img(src=f'https://picsum.photos/300/200?random={seed}')
Grid(*[Card(picsum_img(i),P(f"Image {i}")) for i in range(6)])
Dashboard Example
However, they don't have to be evenly sized! By providing row-span-{int}
and col-span-{int}
we can control how many rows or columns specific grid elements take up. By doing this, we can create a grid that has lots of different shapes and types of elements.
Let's look at a dashboard layout at an examples of this.
Total Users
1,234
Active Now
342
Revenue
$45,678
Conversion
2.4%
Monthly Revenue
User Growth
def StatCard(title, value, color='primary'):
"A card with a statistics. Since there is no row/col span class it will take up 1 slot"
return Card(P(title, cls=TextPresets.muted_sm), H3(value, cls=f'text-{color}'),)
stats = [StatCard(*data) for data in [
("Total Users", "1,234", "blue-600"),
("Active Now", "342", "green-600"),
("Revenue", "$45,678", "purple-600"),
("Conversion", "2.4%", "amber-600")]]
def ChartCard(title):
"A card for a chart. col-span-2 means it will take up 2 columns"
return Div(cls="col-span-2")(
Card(H3(title),Div("Chart Goes Here", cls="h-64 uk-background-muted")))
chart_cards = [ChartCard(title) for title in ("Monthly Revenue", "User Growth")]
sidebar = Form(
H3("SideBar"),
LabelRange("Range For Filters", min=0, max=100),
LabelInput("A search Bar"),
LabelSelect(map(Option, ["Product Line A", "Product Line B", "Product Line C", "Product Line D"]),
label="Choose Product Line"),
LabelCheckboxX("Include Inactive Users"),
LabelCheckboxX("Include Users without order"),
LabelCheckboxX("Include Users without email"),
# This sidebar will take up 2 rows b/c of row-span-2
cls='row-span-2 space-y-5'
)
Container(Grid(sidebar, *stats, *chart_cards, cols=5))
Flexbox
Using Grid for the overall layout, and flex for the individual elements is a powerful pattern. With MonsterUI
you can do quite a bit without knowing anything about flexbox, which is what will be taught here.
However, flexbox is well worth learning about it in more detail. You will run into situations where you need more flexbox knowledge than is covered here to build your vision. Thankfully you can get that knowledge by playing a fantastic tutorial game called FlexBox Froggy!
Forms
Often you want to stack things horizontally. You can use the DivHStacked
component to do this.
DivHStacked
is a helper function for flexbox and creates a div with these classes by default cls=(FlexT.block, FlexT.row, FlexT.middle, 'space-x-4')
.
Form with Input Groups
def InputGroup(label, placeholder='', button_text='Submit', cls=''):
# Div H Stacked makes the label and input show up on the same row instead of putting the input on a newline
return DivHStacked(
FormLabel(label, cls='whitespace-nowrap'),
Input(placeholder=placeholder))
Container(
H3("Form with Input Groups"),
Form(cls='space-y-4')(
InputGroup("Search Users", "Enter username..."),
InputGroup("Filter Tags", "Add tags...", "Add"),
InputGroup("Email List", "Enter email...", "Subscribe"),
Div(*( Button(UkIcon(icon, cls='mr-2'), text) for icon, text in [("rocket", "Submit"), ("circle-x", "Cancel")]), cls='space-x-4')))
Avatar
You can use this same DivHStacked
to align things like text next to images. And you can use DivVStacked
to stack things vertically to create design structures you like. DivVStacked
works by using cls=(FlexT.block,FlexT.column,FlexT.middle)
# DivHStacked makes the a single row so text is to on same line as avatar
DivHStacked(
DiceBearAvatar("user"),
# DivVStacked stacks things vertically together and centers it with flex
DivVStacked(
P("John Doe", cls=TextT.lg),
P("[email protected]", cls=TextT.muted),
P("+1-123-456-7890"), cls=TextT.muted))
Pricing Card
These can be combined with icons and other styling to create larger components like a pricing card.
Pro Plan
$99
per month
- Unlimited users
- 24/7 priority support
- Custom branding options
- Advanced analytics dashboard
- Full API access
- Priority request queue
features = [
"Unlimited users",
"24/7 priority support",
"Custom branding options",
"Advanced analytics dashboard",
"Full API access",
"Priority request queue"
]
def PricingCard(plan, price, features):
"Create a polished pricing card with consistent styling"
return Card(
DivVStacked( # Center and veritcally stack the plan name and price
H2(plan),
H3(price, cls='text-primary'),
P('per month',cls=TextT.muted),
cls='space-y-1'),
# DivHStacked makes green check and feature Li show up on same row instead of newline
Ul(*[DivHStacked(UkIcon('check', cls='text-green-500 mr-2'), Li(feature)) for feature in features],
cls='space-y-4'),
Button("Subscribe Now", cls=(ButtonT.primary, 'w-full')))
DivVStacked(PricingCard("Pro Plan", "$99", features))
Footer
Or you can combine things to make advanced footers that have titles, organized links, and icons!
In this example we add another flex helper function, DivFullySpaced
. DivFullySpaced
is a flex class that puts as much space between items as possible
Company Name
© 2024 Company Name. All rights reserved.
def FooterLinkGroup(title, links):
# DivVStacked centers and makes title and each link stack vertically
return DivVStacked(
H4(title),
*[A(text, href=f"#{text.lower().replace(' ', '-')}", cls=TextT.muted) for text in links])
company = ["About", "Blog", "Careers", "Press Kit"]
resource = ["Documentation", "Help Center", "Status", "Contact Sales"]
legal = ["Terms of Service", "Privacy Policy", "Cookie Settings", "Accessibility"]
Container(cls='uk-background-muted py-12')(Div(
# Company Name and social icons will be on the same row with as much sapce between as possible
DivFullySpaced(
H3("Company Name"),
# DivHStacked makes the icons be on the same row in a group
DivHStacked(*[UkIcon(icon, cls=TextT.lead) for icon in
['twitter', 'facebook', 'github', 'linkedin']])),
DividerLine(),
DivFullySpaced( # Each child will be spread out as much as possible based on number of children
FooterLinkGroup("Company", company),
FooterLinkGroup("Resources", resource),
FooterLinkGroup("Legal", legal)),
DividerLine(),
P("© 2024 Company Name. All rights reserved.", cls=TextT.lead+TextT.sm),
cls='space-y-8 p-8'))
Dashboard
Welcome back, Isaac!
Here's what's happening with your projects today.
Total Projects
12
+2.5% from last month
Hours Logged
164
+12.3% from last month
Tasks Complete
64%
-4.1% from last month
Team Velocity
23
+8.4% from last month
Recent Activity
Sarah Chen completed Project Alpha deployment
2h ago
James Wilson commented on Project Beta
4h ago
Maria Garcia uploaded new design files
6h ago
Alex Kumar started Sprint Planning
8h ago
def StatsCard(label, value, change):
color = 'green' if change[0] == '+' else 'red'
return Card(DivVStacked( # Stacks vertically and centers all elements
P(label, cls=TextPresets.muted_sm),
H3(value),
P(f"{change}% from last month", cls=f"text-{color}-600 text-sm")))
def RecentActivity(user, action, time):
return DivHStacked( # Makes Avatar and text be on same row
DiceBearAvatar(user, h=8, w=8),
P(f"{user} {action}", cls="flex-1"),
P(time, cls=TextPresets.muted_sm))
DivVStacked( # Centers the entire dashboard layout
# Page header
DivVStacked( # Stacks vertically and centers the title/subtitle
H2("Welcome back, Isaac!"),
P("Here's what's happening with your projects today.",cls=TextT.muted)),
# DivHStacked puts all the stats cards on the same row
DivHStacked(*(StatsCard(label, value, change)
for label, value, change in [
("Total Projects", "12", "+2.5"),
("Hours Logged", "164", "+12.3"),
("Tasks Complete", "64%", "-4.1"),
("Team Velocity", "23", "+8.4")]
)),
# Recent activity
Card(*(RecentActivity(user, action, time)
for user, action, time in [
("Sarah Chen", "completed Project Alpha deployment", "2h ago"),
("James Wilson", "commented on Project Beta", "4h ago"),
("Maria Garcia", "uploaded new design files", "6h ago"),
("Alex Kumar", "started Sprint Planning", "8h ago")]),
header=H3("Recent Activity"),
),
cls="space-y-6"
)
Columns
Columns are a great for sections that have a lot of text.
Lorem Ipsum
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor.
Container(
H1("Lorem Ipsum", cls="text-center mb-8"),
# Use 2 columns for the main content
Div(cls="columns-2 gap-12")(
P("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat."""),
DivCentered(cls='mt-8')(
P("""Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.""",
cls=(TextT.lg, TextT.bold, TextT.center, TextT.italic, "text-primary"))),
P("""Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde
omnis iste natus error sit voluptatem accusantium doloremque laudantium."""),
P("""Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit
aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem
sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor.""")))