Styling language specific code blocks with Jekyll

While inspecting the markup of some syntax highlighted code blocks generated by Kramdown and Jekyll, I noticed something I hadn’t before, language-lexer classes:

<div class="language-css highlighter-rouge">
  <pre class="highlight">
    <code>.foo { color: red; }</code>
  </pre>
</div>

This extra hook1 on the <div> element opens up some interesting styling possibilities. A fun use case for this is styling code blocks to look like terminal windows. Assign terminal2 as the language/lexer like so:

```terminal
```

Add the following Sass to your site’s stylesheet:

$terminal-window-height: 30px;

.language-terminal {
  position: relative;
  margin-bottom: 1.5em;
  padding: calc(#{$terminal-window-height} + 1em) 1em 1em;
  border: 1px solid $border-color;
  border-radius: $border-radius;
  box-shadow: 0 0.25em 1em rgba($base-color, 0.25);
  background-color: $base-color;

  &::before {
    content: "\2022 \2022 \2022";
    position: absolute;
    top: 0;
    left: 0;
    margin: 0;
    padding: (0.5 * $terminal-window-height) 0;
    background: mix($base-color, #fff, 25%);
    color: mix($base-color, #fff, 50%);
    font-size: (2 * $terminal-window-height);
    line-height: 0;
    text-indent: (0.5 * $terminal-window-height);
  }

  .highlight {
    margin: 0;
    padding: 0;
    background-color: initial;
    color: #fff;
  }
}

And you’ll get something that looks like this:

[15:34:01] Finished 'site' after 2.18 min
[15:34:01] Starting 'copy:site'...
[15:34:06] Finished 'copy:site' after 4.8 s
[15:34:06] Finished 'build:site' after 2.33 min
[15:34:06] Starting 'reload'...
[BS] Reloading Browsers...
[15:34:06] Finished 'reload' after 5.22 ms

This isn’t limited to language-terminal, and can be applied to any of the other languages and lexers supported by Rouge.


  1. Apparently this was added into Kramdown a year ago. 😐 Who knew? ↩︎

  2. terminal and console are aliases for shell_session and can be used interchangeably when assigning a language for syntax highlighting. ↩︎

Tags:

2 comments

  1. Manuel Monterosso ·

    Great job! Can you give me the color variables for this snippet? As I don’t seem to find them anywhere ^^

  2. Michael Rose ·

    SCSS variables can be found in the source code for this site.

    ref: ./src/assets/stylesheets/_variables.scss

    // Syntax highlighting base16 color variables
    $base00: #f2f2f2;
    $base01: #e3e3e3;
    $base02: #b9b9b9;
    $base03: #ababab;
    $base04: #525252;
    $base05: #464646;
    $base06: #252525;
    $base07: #101010;
    $base08: #7c7c7c;
    $base09: #999999;
    $base0a: #a0a0a0;
    $base0b: #8e8e8e;
    $base0c: #868686;
    $base0d: #686868;
    $base0e: #747474;
    $base0f: #5e5e5e;