Sustainable.devBETA Menu

Posted to Resource on November 8, 2020


Modern layouts with a couple of lines of CSS

Modern CSS is quite incredible. The layouts that can be created with just one or a couple of lines of CSS are leaps and bounds ahead of what was possible with CSS alone not that many years ago.

There are also simple, common layouts that can now be created with only a couple of lines, instead of 10s of lines of CSS. Which, may not save much in terms of page weight, but could certainly speed up the development time and continued maintenance of a website.

Here are a few of our favourites, made with just a couple of lines of CSS.

1. Vertical and horizontal central alignment – the easiest method

It’s one of those seemingly infamously tricky things for developers to learn when starting out. Well, those days are over. One line is all you need (for most modern browsers) to center an object inside another.

.centered-items {
  display: grid;
  place-items: center;
}

View an example on codepen.io
 

2. Responsive stacking columns

Found somewhere in most websites these days, a layout that contains a grid of ’tiles’ that naturally stack into one column for smaller devices.

.parent {
  display: flex;
  flex-wrap: wrap;
}

.child {
  //  flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
  //  If we don't want the items to stretch:
  flex: 0 1 300px;
  //  If we do want the items to stretch:
  flex: 1 1 300px;
}

View and example on codepen.io
 

3. Fluid width content with sidebar

Another great staple found in many webapps that include a fluid width content area and a fluid sidebar with a max-width.

body {
  display: grid;
  grid-template-columns: minmax(150px, 25%) 1fr;
  margin: 0;
}

.sidebar {
  height: 100vh;
}

View and example on codepen.io
 

4. Website stack (header, main, footer)

Your base staple layout. A full-width fixed height header, a fluid height main container and a fixed height footer. The main container fills the height of the browser window to keep the footer at the bottom.

body {
  display: grid;
  height: 100vh;
  grid-template-rows: auto 1fr auto;
}

View and example on codepen.io
 

5. The ‘holy grail’ layout (header, sidebar left, main, sidebar right, footer)

You know the one. Think Facebook, LinkedIn, many news reporting websites etc.

body {
  display: grid;
  height: 100vh;
  grid-template: auto 1fr auto / auto 1fr auto
}

header {
  grid-column: 1 / 4;
}

.left-sidebar {
  grid-column: 1 / 2;
}

main {
  grid-column: 2 / 3;
}

.right-sidebar {
  grid-column: 3 / 4;
}

footer {
  grid-column: 1 / 4;
}

View and example on codepen.io