Skip to content

Instantly share code, notes, and snippets.

Last active July 29, 2023 08:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Script to scan a directory for HTML files, inlining stylesheets into <head>. Useful for Middleman sites.
require "pathname"
require "nokogiri"
def inline_css(html_file, root)
doc = { |f| Nokogiri::HTML(f) }
stylesheet_tags = doc.css("link[rel=stylesheet]")
puts "Inlining css in #{html_file}" if stylesheet_tags.any?
stylesheet_tags.each do |stylesheet_tag|
href = stylesheet_tag["href"]
href = href[1..-1] if
css_file_path = File.expand_path(href, root)
css =
style_tag = "style", doc
style_tag.content = css
stylesheet_tag.add_previous_sibling style_tag
File.write(html_file, doc.to_s)
root = "build/"
Dir.glob(File.join(root, "**", "*.html")).each do |html_file|
inline_css(html_file, root)
Copy link

Thanks for sharing... this worked great for me.

Copy link

pascalw commented Jul 29, 2023

@timothyf cool, great to hear!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment