Explain Codes LogoExplain Codes Logo

2 Column Div Layout: Right Column With Fixed Width, Left Fluid

html
responsive-design
css-grid
media-queries
Alex KataevbyAlex Kataev·Aug 4, 2024
TLDR

Elevate your design with a responsive 2-column layout using CSS Flexbox. The left column will adapt to the available space, while the right column retains a constant 200px width. Here's the minimalist solution:

<div style="display: flex;"> <div style="flex: 1; background: lightblue;">Left Column</div> <div style="width: 200px; background: orange;">Right Column</div> </div>

Media queries for responsiveness

You've got your 2-column layout. but is your site really enjoying life if it's not responsive? Media queries ensure your layout gets its groove on/upholds the harmony on different devices:

@media screen and (max-width: 600px) { .container { flex-direction: column; } }

Your layout is now breaking into a single-column vibe on screens under 600px wide.

Alternative CSS party tricks

Like a clown at a kid's party, CSS boasts a dazzling array of crowd pleasing tricks. Consider these alternatives:

  1. CSS Grid: Bends layout conundrums to its will in no time flat:
.grid-container { display: grid; grid-template-columns: auto 200px; }
  1. Floats: The elder statesperson of CSS layout methods. Sure, it's a little long in the tooth, but it still has a few tricks up its sleeve:
<div style="float: left; width: calc(100% - 200px);">Left Column</div> <div style="float: right; width: 200px;">Right Column</div>

Using calc() for fun and profit

Add some magic to your CSS with calc(). This function lets you perform calculations within your stylesheets, as if you needed another reason to love CSS:

.left-column { width: calc(100% - 200px); /* *Poof* - Your fluid column now fits snugly beside its fixed-width neighbour */ } .right-column { width: 200px; }

Handling content overflow like a champ

Wrestle overflowing content to the ground and maintain your crisp layout with overflow: hidden:

.container { overflow: hidden; /* Floats cleared. Layout breezy. */ } .left-column { overflow: auto; /* Overflow handled. Easy, right? */ }

Using overflow: hidden on the container clears the layout's proverbial throat, containing the columns with ease.

How to keep your layout in line

Floats and margins in harmony

Employ a clearfix to ensure your floated elements know their place and stay therein:

.clearfix::after { content: ""; display: table; clear: both; /* Like Moses parting the Red Sea */ }

Margin gymnastics

Marvel as your layouts perform acrobatic feats of precision with negative margins:

.sidebar { margin-left: calc(-200px + 1em); /* Just a bit of cheeky margin-adjusting wizardry */ }

Creating space for a sidebar while taking into account any necessary padding or margin.