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.
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.
Semi-colon for the last CSS declaration in a declaration block can be omitted.
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.
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 border-width
and #
marks the start of border-color
.
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 <P>
tag.
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?!
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!
By default, you have the html
and body
elements to style in your code!
For many properties, you can omit the px
unit and just write the numeric value.
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!