Here, we list some tips and tricks for CSS code-golfing that can help you get better scores. These tips are curated from numerous sources, many of which are generously shared by some of our awesome CSSBattle-ers: Alex Zaworski, Ilya Streltsyn, Praveen, Stas Lashmanov, Jon Uleis and many more 🙏!
DISCLAIMER: The strategies listed here are not meant to be used in real projects. They mostly help you in CSSBattle code-golfing (expect for few which can be used elsewhere). In real world you'll probably use a minifier to make your files smaller.
Want to add a tip you discovered? Mail us.
Tips & Tricks
The most basic strategy for code-golfing — remove unnecessary spaces, tabs, newlines, etc. These characters are not necessary for the code to work functionally. This is one of the things that minifiers do to your code too.
Omit the last semi-colon
Semi-colon for the last CSS declaration in a declaration block can be omitted.
Omit the closing tags
In most cases, you can omit the closing tag of an element. This works because the Browser closes them for you, to make the HTML valid. Though, be cautious as in some cases seemingly unclosed sibling tags can become parent-child of each other.
Remove Double Quotes
You can remove the quotes from HTML attributes and replace the white-spaces before numbers with a
-. Though, some re-ordering might be required to make things work. This is a very good example of exploiting how parsers understand your code. In the following example, we reorder things such that
+ marks the beginning of
# marks the start of
Shorten selectors with made-up attributes
You can assign made-up attribute to any element to target it specifically in your selectors. Here is an example where you want to select the 3rd
position:fixed beats position:absolute, mostly
In most cases, you might want to absolutely position an element with respect to the window/viewport instead of another element. In such
position: fixed can save you a good 3 characters! Neat, right?!
Play with the units
Experimenting with different units can save you a character or two, and give you that extra edge. For eg.
100px is better written as
25vw for CSSBattle's 400px target width. And guess what, Alex Zaworski also has created a wonderful open-source tool to help you with just this, called unit-golf!
You don't always need to add an HTML element to style!
By default, you have the
body elements to style in your code!
Omit the 'px' unit
For many properties, you can omit the
px unit and just write the numeric value.
<body> has some ancient super-attributes!
There are old deprecated attributes available on
body tag to give background and text color. These can prove deadly in battles!
We'll keep adding more mind-blowing tips here. Check back for more!