CSS (Cascading Style Sheets) are a very powerful way to apply styles to an HTML page. It has the advantage of removing most of the formatting (styling) and putting it in a single location. However, in my first tries I tended to create a lot of styles which where very similar one to each other.
For example, I would write:
p {
margin:0px 10px 5px 10px;
font-size:13px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
color: #000000
}
pre {
margin:0px 10px 10px 10px;
font-size:13px;
color: #000000
}
ol {
font-size:13px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
color: #000000;
}
ul {
font-size:13px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
color: #000000;
}
I wanted to improve and optimize all this. It took me several steps to get it. The first (nearly obvious one since it is described clearly in all CSS tutorials and books) was to group exactly identical styles (like ul
and ol
, in my example), leading to the following:
p {
margin:0px 10px 5px 10px;
font-size:13px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
color: #000000;
}
pre {
margin:0px 10px 10px 10px;
font-size:13px;
font-family: Courier, "Courier New", monospace;
color: #000000;
}
ul, ol {
font-size:13px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
color: #000000;
}
No big deal, but it is reducing the amount of redundancy.
After that point, I was left in the dark with trying to group styles which where not exactly identical and so could not obviously be grouped. What I needed was to understand that a style can be defined in separate (additive) declarations, like:
p {
margin:0px 10px 5px 10px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
}
p {
font-size:13px;
color: #000000;
}
pre {
margin:0px 10px 10px 10px;
font-family: Courier, "Courier New", monospace;
}
pre {
font-size:13px;
color: #000000;
}
Now, it becomes nearly obvious how to combine styles even when they are not fully identical: Group what can be grouped, keep the rest separated.
p, pre {
font-size:13px;
color: #000000;
}
p {
margin:0px 10px 5px 10px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
}
pre {
margin:0px 10px 10px 10px;
font-family: Courier, "Courier New", monospace;
}
The final code for my example is then:
p, pre, ul, ol {
font-size:13px;
color: #000000;
}
p {
margin:0px 10px 5px 10px;
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
}
ul, ol {
font-family: Arial, Helv, Helvetica, Geneva, sans-serif;
}
pre {
margin:0px 10px 10px 10px;
font-family: Courier, "Courier New", monospace;
}
15 lines instead of 21, nearly no redundancy left (none except what I chose to keep for readability); This has been leading to significant simplifications of my style sheets. I hope it will be the case for you too.
Leave a Reply