Stylesheets are not scoped based on where they are included in the page, only based on the rules within them. So the following stylesheet rule always applies to all p
elements on the page, wherever the rule itself appears:
p { font-size: 50%; }
The obvious solution to this is to give each container within your page an ID or class which can be used to scope the rules more tightly. Remember that an ID must always be unique across the rendered page, so any block which might be included more than once on the page should be identified by a class instead (this includes things like the content of a search form, even if your current design has it in a unique placement).
So you might have separate rules like so:
#header p { font-size: 50%; }
#main_content p { font-size: 100%; }
.sidebar_block p { font-size: 90%; }
In general, you'll want to group your style rules by which blocks they apply to, so you will find yourself with lots of rules next to each other with the same prefix. You can save on the redundancy of this by using a server-side CSS pre-processor such as LESS or SCSS (SASS) which supports nested rules.
LESS was originally developed in JavaScript, and SASS/SCSS in Ruby, but implementations of both are available in PHP, e.g. these from leafo.net. Both would allow you to write this, which would be rendered as the same CSS as the above example:
#header {
p { font-size: 50%; }
// other rules within #header
}
#main_content {
p { font-size: 100%; }
// other rules within #main_content
}
.sidebar_block {
p { font-size: 90%; }
// other rules within .sidebar_block
}
Finally, if you are using an HTML5 doctype (and have taken appropriate precautions for older browsers) you can use "semantic" containers instead of div
elements with IDs or classes, so that (along with a CSS pre-processor) you could end up with this (where <header>
, <main>
, and <aside>
are all new elements in HTML5):
header {
p { font-size: 50%; }
// other rules within #header
}
main {
p { font-size: 100%; }
// other rules within #main_content
}
aside {
p { font-size: 90%; }
// other rules within .sidebar_block
}