Skip to content

Instantly share code, notes, and snippets.

@kkoomen
Last active January 12, 2019 15:43
Show Gist options
  • Save kkoomen/a14ea1359213dd9767124cd53e10fabf to your computer and use it in GitHub Desktop.
Save kkoomen/a14ea1359213dd9767124cd53e10fabf to your computer and use it in GitHub Desktop.
Convert css pixel value to rem.
#!/usr/bin/env bash
#
# Convert all your "px" values to "rem" values. Supported filetypes can
# literally be anything, but just use extensions like:
# - file.css.less
# - file.less
# - file.css
# - file.scss
# - file.sass
#
# Usage: ./px-to-rem.sh <destination> <type>
# Example usage: ./px-to-rem.sh /var/www/html/project-name/public/sass/ scss
# ./px-to-rem.sh /var/www/html/project-name/public/sass/ css.less
# ./px-to-rem.sh /var/www/html/project-name/public/sass/ less
# ./px-to-rem.sh /var/www/html/project-name/public/sass/ css
#
# <destination> : Add the path to your directory containing all the css files.
# <type> : Files containing this type of extension will be converted.
#
# 1. Set "font-size: 62.5%;" on your html tag in css to set base-10 font-size.
# 2. Run this script.
# 3. Everything should be converted and nothing should be changed visually.
destination="$1"
filetype="$2"
usage() {
echo "Usage: ./px-to-rem.sh <destination> <type>"
echo "Example usage: ./px-to-rem.sh /var/www/html/project-name/public/stylesheets/ scss"
echo " ./px-to-rem.sh /var/www/html/project-name/public/stylesheets/ css.less"
echo " ./px-to-rem.sh /var/www/html/project-name/public/stylesheets/ less"
echo " ./px-to-rem.sh /var/www/html/project-name/public/stylesheets/ css"
}
if [[ "$destination" == "" ]]; then
echo "<destination> is undefined."
echo
usage
exit 1
fi
if [[ "$filetype" == "" ]]; then
echo "<type> is undefined."
echo
usage
exit 1
fi
for file in $(find $destination -name *.$filetype); do
echo "[$filetype] $file"
perl -i -lpe 'BEGIN {
sub rem {
my ($num) = @_;
($num >= 5 and $num < 9000) ? ($num / 10) . "rem" : $num . "px"
}
} s/(\d+)px/(rem($1))/eg' $file
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment