Journal tags: columns

1

Media queries and multiple columns

By far the most common use of media queries is to execute CSS based on viewport width (using min-width or max-width). Lately there’s been more talk about using media queries based on height as well.

Paul talked about using min-height media queries to adjust content appearing above the fold. Owen Gregory wrote his superb 24 Ways article on using viewport proportions and device-aspect-ratio for media queries. Trent has documented his use of horizontal and vertical media queries to bump up the font size for wide and tall viewports.

One of the areas where I’ve found height-based media queries to be quite handy is in combination with another CSS3 module: multiple columns.

Splitting text over multiple columns is not something to be done lightly on a screen-based display. If the columns drop below the viewport then the user has to scroll down, scroll back up, scroll down again …you get the picture. It works fine in print but it’s not something that should be attempted on the web unless the entire text is visible at one time.

Well, with media queries we can get a pretty good idea of whether the text will fit on the viewport …assuming we know the length of the text.

Here’s an example (thanks to Space Ipsum for supplying the text). It splits the text into two columns if the viewport has enough width and height:

@media all and (min-width: 40em) and (min-height: 36em) {
    [role="main"] {
        column-count: 2;
        column-gap: 2em;
    }
}

If the viewport is wider still, the text can be split over three columns. In this case, the test for height can actually smaller because the text is spreading over a wider area, meaning the overall height of the text is shorter:

@media all and (min-width: 65em) and (min-height: 25em) {
    [role="main"] {
        column-count: 3;
        column-gap: 2em;
    }
}

The actual CSS is more verbose than that: vendor prefixes are still required. You can grab the example from Github if you want to have a play around with it.