Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 3 CSS SELECTORS AND INHERITANCE

Subclass Selector


Problem


You want a class of elements to be styled with common rules. You also want these elements to be
divided into subclasses and styled with specialized rules that may override the base rules.

Solution HTML CSS


You can assign classes to elements in your
HTML code using the class attribute. A
class attribute can contain an unlimited
number of space-delimited classes. The order
of the classes in the attribute is not important.
For readability, I recommend listing the base
class first followed by its subclasses. The
classes assigned to an element do not have to
be related, but the code is more logical if you
organize them into classes and subclasses.


To select all elements assigned to a base class,
use the universal selector followed by the dot
operator, followed by the name of the base class,
followed by the dot operator, followed by the
name of the subclass. I call this chaining
together classes. There is no limit to the number
of chained classes. The order of the classes in
the selector is not important. For readability, I
recommend listing the base class first followed
by its subclasses. The classes you chain together
do not have to be related, but the code is more
logical if they are organized into base classes
and subclasses.

Pattern HTML CSS


*.class { SHARED_BASE_STYLES }
*.class.subclass.etc { SUBCLASS_STYLES }

Location You can apply this design pattern to any element.^


Advantages You can use this design pattern to build a hierarchy of rules based on classes and subclasses.
As in object-oriented programming, subclassed elements “inherit” the rules from their base
class and their subclass. CSS cascading order ensures rules from the subclass override the
rules in the base class.


Example In the example, all paragraphs are assigned to the button class. Each one is also assigned to
the square, rounded, and go subclasses. All paragraphs assigned to the button class share the
same base rules assigned by .button, such as width:175px. Each subclassed paragraph is
assigned to specialized rules through
.button.square, .button.rounded, or .button.go.
For example, each subclass assigns a different background to its type of button. Some
specialized rules, like margin and line-height, override base rules.


Related to Class Selector

Free download pdf