You can group styles common to different rules into their own classes to save repeating yourself. CSS2-compliant browsers can reference multiple classes within individual elements.
For example:
<div id="nav" class="nav center">...</div>
This ability to reference multiple classes gives authors newfound options when styling their content. For elements that share the same styles (text-align:center
for example), you can group these shared styles into one shared class. So this:
<style type="text/css">
<!--
.nav{color:red; text-align:center;}
.main{color:#000; text-align:center;}
-->
</style>
...
<div id="nav" class="nav">...</div>
<div id="main" class="main">...</div>
Becomes this after grouping the common center style into one shared class:
<style type="text/css">
<!--
.nav{color:red;}
.main{color:#000;}
.ctr{text-align:center;}
-->
</style>
...
<div id="nav" class="nav ctr">...</div>
<div id="main" class="main ctr">...</div>
The third .ctr
class groups the common styles (in this case the center declaration) into a class now shared by two elements. The additional class saves space by eliminating redundant common declarations, which can add up for larger style sheets. In effect, you are normalizing your CSS.
This technique of grouping common styles within shared classes is supported by most modern browsers. You can combine shared classes with grouping of selectors and declarations and shorthand properties to create optimized CSS rules.
Further Reading
- Advanced CSS Optimization
- Summary of chapter on optimizing CSS from Speed Up Your Site: Web Site Optimization with more advanced techniques, including substitution, CSS2 menus, and CSS layout control.
- CSS Home Page
- From the W3C
- CSS Optimization
- Summary of chapter on optimizing CSS from Speed Up Your Site: Web Site Optimization.
- Cascading Style Sheets, level 2 CSS2 Specification
- The CSS specification, from the W3C. By Bert Bos et al.
- CSS Support Charts
- Eric Meyer. The master CSS reference grid.
- CSS: The Definitive Guide
- Eric A. Meyer, (O’Reilly, 2000). A great introduction to CSS which includes descriptions of these shorthand properties. Eric tells me he is working on a new edition. See also Meyerweb.com.
- CSS: Group Selectors and Declarations
- By grouping CSS selectors that share the same declaration and declarations that share the same selector you can apply multiple declarations to multiple selectors to optimize your style sheets.
- CSS: Use Shorthand Properties
- You can use shorthand properties like
font
andborder
in CSS to shrink your style sheets.
Hello Sir,
I want this site in center without table
can you explain how I can do a center in div style?
Regards
Vinay
Any ideas how you could target an element only with both classes applied in CSS?