December 5, 2014 in CSS

CSS3 Inheritance Tips and Tricks

It’s easy to overlook the cascading features of stylesheets. Most developers are aware of the inherit keyword but there are a few new inheritance features in CSS3 you may not be aware of…

property: inherit;

The inherit keyword means “use whatever value is assigned to my parent”. If no value was explicitly defined on the parent element, the browser works up the DOM tree until the property is found. Ultimately, it ends at the browser default, e.g.

1
2
3
4
5
6
7
8
9
10
11
#myparent
{
    margin: 10px;
    border: 1px solid #000;
}
/* use the same border as the parent */
#myparent p
{
    border: inherit;
}

In practice, it’s rarely necessary to use inherit. Many of the more useful properties automatically cascade down, e.g. fonts, font sizes, colors, etc.

inherit is safe to use. It’s not supported in IE6 and IE7 but your design is unlikely to break without it.

property: initial;

Ooo, a shiny new CSS3 keyword! initial sets a property back to its starting value — the default defined by the browser, e.g.

1
2
3
4
5
6
7
8
9
10
body
{
    font-size: 0.5em;
}
/* reset paragraphs to 1em */
p
{
    font-size: initial;
}

Is it useful? Potentially, although you can’t necessarily depend on all browsers having the same default value.

Support is reasonable — Chrome, Firefox, Safari and Opera 15+. It won’t work in IE, but I’m struggling to think of a situation where that would be a catastrophic problem.

property: unset;

This is a slightly unusual one. When unset is used, it acts as if it were inherit when an inherited value is available. If it can’t find one — for example, it’s a non-inherited property such as box-shadow — it acts like initial and applies the default browser value.

Admittedly, I can’t think of many uses for unset and it has little support at this time.

all: [ inherit | initial | unset ];

Finally, all is a property rather than a value. You can assign either inherit, initial or unset to affect all properties, e.g. to reset every CSS property back to the browser default:

1
2
3
4
#mywidget
{
    all: initial;
}

This could be an alternative to scoped CSS if you’re adding third party widgets to a page and want to avoid stylesheet clashing.

Unfortunately, you won’t be able to depend on consistent cross-browser support for some time yet, but it could be a useful property to watch.

Source Link: http://www.sitepoint.com/css3-inheritance-tips-tricks/




By browsing this website, you agree to our privacy policy.
I Agree