Friedrich Ewald My Personal Website

Change font size depending on post length

One of the things that I like about Twitter is that the font size changes depending on the length of the tweet. Yesterday, I tried to achieve the same thing for this Jekyll based blog and came up with the following solution. First, I created a plugin (in the folder _plugins) and registered it as Liquid filter with the following code:

module Jekyll
  module PostFilter
    def post_class(input)
      # Catch invalid posts
      return 'default' if input.nil?
      
      if input.size < 32
        return 'large'
      elsif input.size < 64
        return 'medium'
      else
        return 'default'
      end
    end
  end
end

Liquid::Template.register_filter(Jekyll::PostFilter)
As a next step I changed the post.html template to this:
<p itemprop="articleBody" class="{{content | post_class }}">
  {{ content | remove: "<p>" | remove: "</p>" }}
</p>
It is important to remove the <p> tags because they cannot be nested in valid HTML and Jekyll adds their own tags to post content. Finally, I created some SCSS to change the font-size based on the CSS class.
/* Post pages */
div.post {
    p.default {
        font-size: 1em;
    }
    p.medium {
        font-size: 1.6em;
    }
    p.large {
        font-size: 1.8em;
    }
}


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.