Minify inline style CSS using liquid

Minify inline CSS using Liquid for better legibility and up to 80% compression with a simple snippet.

Virgil Dubois

Virgil Dubois

Shopify theme developer

Cover for Minify inline style CSS using liquid

To handle section instances dynamic styles, I often rely on a good old style tag

tag. Often tried to master the art of whitespace control but there's nothing you can really do when consecutive Liquid tags are used. So I researched and came up with a minification snippet in order to increase legibility of these style tags with a bonus of a small compression Did some tests, barely managing to make the chrome extension work and I got results from 1 to 3ms with a CSS payload up to 64kB with 30 to 80% of compression factor depending on the amount of whitespace present, pretty free in my opinion

{% capture originalCss %}
  {% # CSS inside %}
{% endcapture %}

{% liquid
  assign cssChunkList = originalCss | strip_newlines | split: ' ' | join: ' ' | split: '*/'
  assign minifiedCss = ''
  for cssChunk in cssChunkList
    assign minifiedCss = minifiedCss | append: cssChunk | split: '/*' | first | strip
  endfor
  assign minifiedCss = minifiedCss | replace: "; ", ";" | replace: "} ", "}" | replace: "{ ", "{" | replace: " {", "{" | replace: ': ', ':' | replace: ';}', '}'

  style
    echo minifiedCss
  endstyle
%}

Hope it prove useful to you someday !

Feel free to drop by anytime and don't forget to brind your ideas.

Feelfreetodropbyanytimeanddon'tforgettobrindyourideas.

Join us and be part of a community that values authenticity, collaboration, and innovation.