Choosing the Elements You Want to Style: Writing Selectors

A typical stylesheet, regardless of its scope, is a series of rules structured as follows:

selector { property: value; property: value; [ ... ] }

The bad news—and the bane of many newcomers to CSS—is that this structure is terse to the point of impenetrability.

The steep learning curve of CSS syntax is rewarded with the ability to affect a page’s presentation with a superlative degree of granularity. Any selector can point to any arbitrary set of elements within a page, and CSS properties can accomplish anything within the limits of an implementer’s experience and imagination, when put to thoughtful use.

Note

The concepts explained briefly here are taken up in much greater detail in Applying Taxonomy Through the Cascade.

Parents, Children, and Siblings: Element/Node Relationships

The section Tags, Elements, and Attributes introduced the idea of element nesting for the purpose of explaining how tags-inside-tags need to be written. Element nesting opens to door to one of the most important aspects of applied HTML and CSS:

It is not only allowed but actually encouraged to “wrap” stretches of clearly related content in elements set aside for just that purpose, and to assign descriptive ids and/or classes to such wrappers.

When such “semantically appropriate” elements are used to enclose content, new relationships are created in the document tree, thereby increasing the number of CSS selectors that can be used in the course ...

Get HTML & CSS: The Good Parts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.