Last Updated: September 09, 2019
·
4.277K
· Ionut-Cristian Florescu

A very simple CSS grid with stylus

Twitter Bootstrap is awesome, but sometimes simpler is better and using a full-fledged system might be a bit overkill. You don't need a rich responsive and flexible CSS framework, you just need a plain grid layout and you want to keep your CSS lean.

You just want those basic CSS layout classes, but aren't in the mood to DIY.

Well, if you're on Node.js and are using stylus with nib, feel free to use these lines:

// Defaults

gridColumnCount ?= 12
gridColumnWidth ?= 60
gridPadding     ?= 20

// Grid, row, cell

.l-grid
  width unit(gridColumnCount * (gridColumnWidth + gridPadding), px)
  margin 0 auto

.l-row
  margin unit(gridPadding, px) 0
  clearfix()
  &.l-compact
    margin 0

.l-cell
  float left
  display inline
  width (gridColumnWidth)px
  margin 0 unit(gridPadding / 2, px)

  .l-row
    margin 0 unit(-(gridPadding / 2), px) unit(gridPadding, px)
    &.l-compact
      margin-bottom 0

  // Generate span & offset classes
  for i in 1..gridColumnCount
    unless i is 1
      &.l-span-{i}
        width unit(i * gridColumnWidth + (i - 1) * gridPadding, px)
    unless i is gridColumnCount
      &.l-offset-{i}
        margin-left unit(gridPadding / 2 + i * (gridColumnWidth + gridPadding), px)

...or get them directly from this GitHub page.

You can use the generated classes in your HTML like this:

<div class="l-grid">
  <div class="l-row">
    <div class="l-cell">
    <div class="l-cell">
    ...
    <div class="l-cell">
  </div>
  <div class="l-row">
    <div class="l-cell l-offset-3">
    <div class="l-cell l-offset-1 l-span-2">
    ...
    <div class="l-cell">
  </div>
</div>

Rows can also be nested, like this:

<div class="l-grid">
  <div class="l-row">
    <div class="l-cell">
    <div class="l-cell">
    ...
    <div class="l-cell">
  </div>
  <div class="l-row">
    <div class="l-cell l-offset-3">
    <div class="l-cell l-offset-1 l-span-2">

      <!-- Nested row -->
      <div class="l-row l-compact">
        <div class="l-cell">Nested cell content 1</div>
        <div class="l-cell">Nested cell content 2</div>
        ...
        <div class="l-cell">
      </div>

    ...
    <div class="l-cell">
  </div>
</div>

3 Responses
Add your response

Stylus looks like a cleaner version Sass. I loved the existential operator when defining the defaults. I will definitely try this next time instead of going directly to Bootstrap. Thanks for sharing :)

over 1 year ago ·

Thanks for reading, Jonah!

over 1 year ago ·

Nice. This can be easily turn into full grid system. Like..

cell-2 = cell * 2

cell-3 = cell * 3

over 1 year ago ·