The best way to start learning to write CSS, element selectors match the HTML tags you already know. As an example, if you want to influence the appearance of only h1
elements via a stylesheet, you can write:
h1 { color: firebrick; }
… in a linked or embedded stylesheet.
Element selectors – officially referred to as element type selectors – are crude, but very powerful. Common mistakes when applying them include:
- The name of the selector must exactly match the name of the element.
image { … }
will not affect the appearance of<img>
tags, butimg { … }
will. - Be careful not to confuse the element with a common attribute when making selections.
a { … }
selects links;href
is an the attribute of the tag, not the name of the element, and can’t be used as an element selector. - Avoid being caught in minutia and redundancy: work from the “largest” selector down. That is, start your stylesheet with rules for the
body
orhtml
elements, setting common colors and fonts there, using the principle of inheritance to ensure that other elements have the same appearance without having to explicitly set them. For example:body { font-family: Oxygen, sans-serif; }
is enough to ensure that almost every element on the affected page is rendered in the Oxygen font. - Once you have these main rules created, you don’t need to keep repeating them for other elements.
- Be aware of exceptions: changing the color of links requires that you use the specific
a
selector; trying to affect them through thebody
or other element selectors does not work. Similarly, thekbd
tag uses a reserved monospaced font when displaying its content, and won’t be affected by stylesheet font-family declarations for elements it may be inside of.
As a general rule, element type selectors are used to create “base” appearances for web sites, with more refined rules and exceptions left for more advanced selectors.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.