Multiple selectors and inheritance in CSS

Combining multiple selectors

CSS also offers the possibility of combining selectors. It is possible to select a paragraph that has the class info with p.info {}, or combine several classes by adding a second class to an HTML element (p.info.caps {}). Thus it is possible to format very specific areas of a page.

In our example the paragraph has the classes info and caps. Our CSS code assigns font-size:11px to all paragraphs, border:2px solid blue; to all elements with the class info and font-variant:small-caps; to all elements with the class caps.

Alternative Stylesheet

Our example selects every paragraph with the classes info and caps and adds a blue background color ( background-color: blue; ), and 4 pixel inner distance ( padding: 4px; ).

Inheritance

Another special feature of CSS is inheritance, which means that an element always inherits properties of its parent. Note that not all properties can be inherited.

Every element that hasn't go its own font-size property will now have a font-size of 13px. This saves quite a lot of typing, especially because the font does not change that often. In the following example, the p inherit the text color. They don't inherit the background-color.

The class black-bg assigns a black background with white text-color to the HTML element. The class white-bg does the opposite. A font-size is assigned to the paragraph.

The combination of selectors and inheritance can also be connected, which gives us the opportunity to select nested HTML elements. For example, one can format headings that are in a specific div-container.

Only the headings in the HTML element with the ID content will be colored red.


Continue to part 3






Comment