{ "id": "guide/style-precedence", "title": "Style Precedence", "contents": "\n\n\n
When there are multiple bindings to the same class name or style attribute, Angular uses a set of precedence rules to determine which classes or styles to apply to the element.\nThese rules specify an order for which style and class related bindings have priority.\nThis styling precedence is as follows, from the most specific with the highest priority to least specific with the lowest priority:
\nTemplate bindings are the most specific because they apply to the element directly and exclusively, so they have the highest precedence.
\nBinding type | \nExample | \n
---|---|
Property binding | \n<div [class.foo]=\"hasFoo\"> <div [style.color]=\"color\"> | \n
Map binding | \n<div [class]=\"classExpression\"> <div [style]=\"styleExpression\"> | \n
Static value | \n<div class=\"foo\"> <div style=\"color: blue\"> | \n
Directive host bindings are less specific because you can use directives in multiple locations, so they have a lower precedence than template bindings.
\nBinding type | \nExample | \n
---|---|
Property binding | \nhost: {'[class.foo]': 'hasFoo'} host: {'[style.color]': 'color'} | \n
Map binding | \nhost: {'[class]': 'classExpr'} host: {'[style]': 'styleExpr'} | \n
Static value | \nhost: {'class': 'foo'} host: {'style': 'color: blue'} | \n
Component host bindings have the lowest precedence.
\nBinding type | \nExample | \n
---|---|
Property binding | \nhost: {'[class.foo]': 'hasFoo'} host: {'[style.color]': 'color'} | \n
Map binding | \nhost: {'[class]': 'classExpression'} host: {'[style]': 'styleExpression'} | \n
Static value | \nhost: {'class': 'foo'} host: {'style': 'color: blue'} | \n
In the following example, binding to a specific class, as in [class.special]
, takes precedence over a generic [class]
binding.\nSimilarly, binding to a specific style, as in [style.color]
, takes precedence over a generic [style]
binding.
Specificity rules also apply to bindings even when they originate from different sources.\nAn element can have bindings that originate from its own template, from host bindings on matched directives, and from host bindings on matched components.
\nBindings take precedence over static attributes because they are dynamic.\nIn the following case, class
and [class]
have similar specificity, but the [class]
binding takes precedence.
Higher precedence styles can defer to lower precedence styles using undefined
values.\nFor example, consider the following template:
Imagine that the dirWithHostBinding
directive and the comp-with-host-binding
component both have a [style.width]
host binding.
If dirWithHostBinding
sets its binding to undefined
, the width
property falls back to the value of the comp-with-host-binding
host binding.
If dirWithHostBinding
sets its binding to null
, Angular removes the width
property entirely.