By combining the grouping of selectors that share the same declaration and declarations that share the same selector you can apply multiple declarations to multiple selectors. This technique allows you to create compact yet powerful CSS rules. This tip combines Group Selectors with Group Declarations into one powerful technique.
So this:
body {font-size: 12px; }
body {font-family: arial, helvetica, sans-serif;}
th {font-size: 12px; font-family: arial, helvetica, sans-serif;}
td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
Becomes this:
body, th, td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
Even better, use shorthand properties to create an optimized CSS rule:
body,th,td{font:12px arial,helvetica,sans-serif;}
Note that well-behaved browsers don’t need the th and td selectors because the body rule is inherited by any tables within the body. However, Netscape 4.x does not reliably inherit styles within tables, thus the additional selectors. You could ignore Netscape 4.x, and some leave off helvetica to create a minimalist rule:
body{font:12px arial,sans-serif;}
Note also that we prefer using relative units for fonts for better accessibility, like ems. You can combine grouped selectors and declarations with shorthand properties, contextual, descendant, and type selectors to create powerful yet compact rule-based styles.
There is one other grouping technique that you can use to shrink your styles. We’ll cover that technique in an upcoming tweak.
Further Reading
- Cascading Style Sheets, level 2 CSS2 Specification
- The CSS specification, from the W3C. By Bert Bos et al.
- CSS Home Page
- From the W3C
- CSS Optimization
- Summary of chapter on optimizing CSS from Speed Up Your Site: Web Site Optimization.
- CSS: Group Declarations
- You can group declarations that share the same selector in CSS to shrink your style sheets.
- CSS: Group Selectors
- You can group selectors that share the same declaration to save space in your CSS files.
- CSS: Use Shorthand Properties
- Shows how to abbreviate your CSS declarations with font, border, etc.