Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 3 CSS SELECTORS AND INHERITANCE

Visual Inheritance


Problem You want the background of a child element to be the same as its parent.


Solution CSS automatically layers elements transparently. Child elements are layered on top of parent
elements. If margins or positioning cause sibling elements to overlap, following siblings
overlap previous siblings. For floated and positioned elements, you can set the layering
explicitly using the z-index property. This is a design pattern built into CSS. You do not need
to do anything to take advantage of it.
The background-color property defaults to transparent, and the background-image property
defaults to none. This allows the background of an element’s ancestors to show through. In
other words, a browser renders child elements in transparent layers above parent elements
unless you set a child’s background-color to a color, or you set its background-image to an
image.
Since child elements are nested within parent elements, each child element visually inherits
the borders and padding of its parent. In other words, a parent’s borders and padding
surround its children. If a child has a transparent background and no borders, it appears as if
the parent’s borders and padding are the child’s borders and padding. Without borders
around a child, you cannot tell where the parent’s padding area ends and the child’s padding
area begins. Once you add borders to a child element, it no longer visually inherits the borders
and padding of its parent because you can see precisely where the parent ends and the child
begins.


Pattern You do not need to do anything to use visual inheritance because background-color defaults
to transparent and background-image defaults to none. When you want a child element not
to visually inherit the background of its parent, you can set the element to its own background
color or image as follows:
SELECTOR { background-color:COLOR;
background-image:url("FILE.EXT"); }


Location This design pattern applies to all elements.


Example In the example, the division has a gold background, and all its descendant elements visually
inherit the background—except for the code element, which is assigned to the firebrick
background color. Notice that I assigned background-color:transparent and background-
image:none to the paragraph, label, and span. I did this to show these rules in action. You do
not typically need to assign these rules in your code because background-color:transparent
and background-image:none are the default for all elements. On the other hand, you can use
these rules whenever you want to reset an element to a transparent background after another
rule assigned it to a background color or image.


Related to Inheritance

Free download pdf