Skip to content

Instantly share code, notes, and snippets.

@taoky
Last active July 12, 2025 18:19
Show Gist options
  • Save taoky/8835a3f8eee01d0e8b569d46237388f3 to your computer and use it in GitHub Desktop.
Save taoky/8835a3f8eee01d0e8b569d46237388f3 to your computer and use it in GitHub Desktop.
jekyll keep image aspect-ratio to avoid CLS
# Initially generated by LLM
# Put in _plugins/ and add fastimage and nokogiri to deps
require 'fastimage'
require 'nokogiri'
Jekyll::Hooks.register %i[pages posts], :post_render do |page|
next unless page.output_ext == '.html'
doc = Nokogiri::HTML5.parse(page.output)
changed = false
doc.css('img:not([height])').each do |img|
src = img['src']
next if src.nil? || src =~ %r{^https?://}
path = File.join(page.site.source, src)
next unless File.exist?(path)
w, h = FastImage.size(path)
next unless w && h
img['style'] = [img['style'], "aspect-ratio:#{w}/#{h};"].compact.join
changed = true
end
page.output = doc.to_html if changed
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment