Working with Styles
Style Attributes
The style element supports several attributes. The type attribute specifies the MIME type of the style sheet language, the media attribute specifies the device used to render the document, and the title and id attributes provide a label for the style sheet that can be used in programming. MIME types are a system for indicating document formats. For CSS, the MIME type is “text/css“. The media, title, and id attributes are all optional. If you don’t specify a value for the media attribute, the style sheet is applied to all output media. So long as you are not directing your page to a specific type of output device, you do not need to include the media attribute. Tutorial
Style Inhertiance
If a style is not specified for an element, it inherits the style of its parent element. This effect, known as style inheritance, causes style declarations to cascade down through a document’s hierarchy. For example, if you want to set the text color of every element on a page to blue, you could use the declaration
body {color: blue}
Every element within the body element (which is to say every element on the page) would inherit this style. To override style inheritance, you specify an alternate style for one of the descendant elements of the parent. The styles
body {color: blue}
p {color: red}
would change the text color to blue for every element on the page except for
paragraphs and for any element contained within a paragraph. You can also
override style inheritance by using the !important property as you do for style precedence.
Using Selectors
CSS allows you to work with a wide variety of selectors to match different combinations of
elements. For example, if you want to apply the same style to a collection of elements,
you can group them by entering the elements in a comma-separated list. This feature allows
you to replace a set of repetitive declarations, such as:
h1 {font-family: sans-serif}
h2 {font-family: sans-serif}
h3 {font-family: sans-serif}
h4 {font-family: sans-serif}
h5 {font-family: sans-serif}
h6 {font-family: sans-serif}
with a single declaration:
h1, h2, h3, h4, h5, h6 {font-family: sans-serif}
You can also combine grouped and ungrouped selectors. In the following example, the h1 headings are displayed in a red sans-serif font, while the h2 headings are displayed in a blue sans-serif font:
- h1, h2 {font-family: sans-serif}
- h1 {color: red}
- h2 {color: blue}
Placing common styles in a single declaration is useful for simplifying your style sheet.
