Skip to content

Tyssen Design — Brisbane Tyssen Design logo

[email protected] (07) 3300 3303

How do I make my CSS file smaller?

By /

The key feature of Cascading Style Sheets and probably the one not realised by most newcomers to CSS is that certain style properties are inherited. This means that style properties (mostly those relating to styling text including color, font-size, text-alignment etc.) set on a parent element are inherited up by every descendant element (any element contained within the parent whether directly or indirectly).

You only need to specify a different style on a descendant element when you want it to be different in some way from the styles set on the parent.

That means that you don't need to specify the same styles for every single element on a page, e.g.:


.style1 {
  background-color: #FFF;
  font-size: 11px;
  font-weight: bold;
  font-family: verdana, arial, sans-serif;
  color: #666;
  padding: 4px;
}

.style2{
  background-color: #FFF;
  font-size: 11px;
  font-weight: bold;
  font-family: verdana, arial, sans-serif;
  color: #333;
  padding: 4px;
}

.style3 {
  background-color: #FFF;
  font-size: 11px;
  font-weight: bold;
  font-family: verdana, arial, sans-serif;
  color:#333399;
  padding: 4px;
}
								

The above could be simplified down to:


#parentElememt {
  background-color: #FFF;
  font-size: 11px;
  font-weight: bold;
  font-family: verdana, arial, sans-serif;
  padding: 4px;
}

.style1 { color: #666; }

.style2 { color: #333; }

.style3 { color:#339; }
								

The only thing different between the three styles is the colour, so that’s the only thing we need to specify. We’ve now reduced the numer of lines of code from 25 down to 10!

In the case of font styling, it’s best to set these styles on the body element because they are picked up by every element throughout your site, e.g.:


body {
  font: bold 83%/140% verdana, arial, sans-serif;
  color: #333;
}
								

Then in most cases, you’ll only need to specify a font-size or change of colour for other elements on the page. Having set a percentage for the font-size in the body, we can then use % or ems to scale the font-sizes throughout our site. It is better to use a relative font-size unit rather than pixels (px) because Internet Explorer can’t resize text set in that unit.

You’ll also notice that the style I’ve given for the font in the example above is all on one line. That’s another way to make your CSS file size smaller: shorthand CSS.

Like to say hello? Give us a call on (07) 3300 3303, send us an email to enquiries@tyssendesign.com.au, or a message by filling in the form below.