How to set a fixed width column with CSS flexbox
Define a fixed width column in a CSS flex container using flex: none;
and width: <desired-width>;
. This technique assures that your column remains un-flexed and maintains a constant width:
Incorporate .fixed-width
to your designated element:
The glory of flex: none;
is in its brevity and impact, restraining your item's dimension between the Scylla and Charybdis of different screen sizes and container dimensions.
Maximum settings for minimal regrets
Flex-basis: The Iron Throne of width
In the grand game of flexboxes, flex-basis
is the king. Claim its throne by using this property for specifying the sizes of your fixed columns instead of the common width
.
Using max-width: Walk the (responsive) line
Combine max-width
and width:100%
for a responsive yet constrained element. This way, your element can graciously adapt to various screen sizes up to an upper limit:
Always keep your media queries close for those times you want to modify flex-basis
or max-width
on different screen sizes:
Account for box model: border != chaos
Remember to account for the box model (padding, margin, border) when setting widths. Just like how a Lannister always pays his debts, a good developer always pays attention to the box model:
min() function: shrink and grow young again
To keeps things lively and responsive, use the min()
CSS function:
Lastly — like a fourth wall-breaking Deadpool — always review and test your CSS to ensure it inoculates against eccentric scenarios, devices, and contexts.
Tips for a flexible life
Flex shorthand: the Swiss knife of flex
The flex
shorthand ensures you don't make an exhibition of verbosity and makes your intentions obvious:
Introduce CSS variables: friends you can rely on
Use CSS variables for values referenced by multiple styles to keep your codebase DRY — Don't Repeat Yourself — and your sanity intact:
Embrace fluid layouts: resistance is futile
If Captain Picard tasked you with building a fluid layout, ditch fixed widths for percentages. By doing this, your layout adapts like a Borg to available space:
Community: your code dojo
Stay involved and heed community feedback. Somebody else might have faced the same conundrums before and could have knowledge that will save you from reinventing the wheel.
Was this article helpful?