[nolan@nprescott.com] $  cat weblog archive feed

CSS Tip of the Day

2021-03-22

A quick note about a single piece of HTML and CSS that I've used only enough that I have to recheck my notes each time to remind myself.

I only begrudgingly acknowledge most new browser features but one feature I've really been able to get behind is flexbox! Specifically I like the ability to position elements horizontally adjacent and have them flex into a vertical arrangement on small screens.

Given markup like the following:

<div class="container">
  <div class="child">
    left hand side!
  </div>

  <div class="child">
    right hand side!
  </div>
</div>

It is easy to position them like this:

left hand side!
right hand side!

Using the following CSS:

.container { display: flex }
.child { flex: 1 1 }
@media (max-width: 950px) { .container { flex-flow: column } }

The effect is that while the screen remains above 950 pixels in width both boxes appear adjacent taking equal width on screen. Under 950 pixels the elements collapse into a vertical configuration like this:

left hand side!
right hand side!

I first used a similar technique in writing about deadlocks and then again in looking at Asteroids. Once you know how to do it the possibilities just keep cropping up! I'm actually pretty happy with how those write-ups are readable in browsers that don't support flexbox too.

Funnily enough, as I wrote this out I realized I had extraneous parameters in my CSS. I've cleaned it up above but it seems strange that I've been successfully using "bad" CSS for years. A real peril of copy-pasting things I find purporting to explain CSS I guess.