How can I have two fixed width columns with one flexible column in the center?
With CSS Flexbox, we can achieve two fixed-width columns and a flexible center column. Here's how to do it: set display: flex;
on the container, flex: 0 0 auto;
and a specific width
for the side columns, and allow the center column to fill up remaining space with flex-grow: 1;
.
In this setup, the center column will adjust it's width to fill up the extra space after the fixed-width side columns.
Understanding Flex: 0 0
and avoiding width
Mustering Flexbox powers, we ensure efficient and easy responsive layouts. Flex: 0 0 [width]
makes a flex item keep it's initial width, meaning it won't grow or shrink. In flexbox, we exchange width
for flex-basis
because it gives us a better control and predictability over our layout designs.
Making it responsive
To keep your layout working on varying screen sizes, apply a max-width
on the container and flex-shrink: 0
on fixed-width columns. This prevents them from feeling too cozy and shrinking on smaller screens. Also, ensure to add max-width: 100%;
to images inside flex items to prevent them from overflowing their containers.
Dynamic column visibility
For a sizzling user experience, add functionality to hide or show columns at whim (JavaScript can help here). Give separate borders to different columns to provide visual clarity, imagine drawing lines in the sand to mark territories 😉
Browser support
Remember to validate the browser compatibility of the Flexbox features you use. Although Flexbox has a good support band, some features might play different tunes on older browsers. Testing across various browsers will ensure a harmonious layout performance.
Going beyond the basics
For some more secret sauce, let's look at additional techniques:
- Aligning items: With
justify-content
andalign-items
, you can align your items just the way you want. - Controlling flexibility:
Flex-basis
and theflex
shorthand give you power to dictate how space is strutted around when the container width changes. - Toggle visibility: Show or hide columns at your control, preserving the layout's flow.
Dive into a live demo
Hands-on experience breaks the ice with new knowledge. Here's a JSFiddle link to interact with the layout: Flexy Layout Interaction. Explore different scenarios:
- Just the basics: The base layout with fixed and flexible columns.
- The talkative columns: How adding content alters the center column's width.
- Responsive check: See how the layout holds up when the viewport size changes.
Sprinkle in some customization
To make it your own, a few CSS tweaks can go a long way:
- Use
border-left
andborder-right
on the center column for a distinguished look. - Tweak
margin
andpadding
, because everyone needs a little personal space. - Implement media queries to change things up at different breakpoints. Because variety is the spice of life, right?
Was this article helpful?