CSS @property
The @property
CSS rule is used to define custom properties with additional options, such as setting a default value, specifying an inheritance behavior, and defining the type of the property. It enhances CSS variables by allowing more control over their behavior.
Key Topics
Defining a CSS Property
The @property
rule defines a custom property, specifying its name, default value, and other attributes.
<style>
@property --custom-color {
syntax: '';
inherits: false;
initial-value: #007BFF;
}
.example {
color: var(--custom-color);
}
</style>
<div class="example">This text uses a custom property with @property.</div>
Explanation: The @property
rule defines --custom-color
as a color property with an initial value of #007BFF
. The property does not inherit its value.
Default Values
You can specify default values for custom properties using the initial-value
attribute in the @property
rule.
<style>
@property --custom-padding {
syntax: '';
inherits: true;
initial-value: 10px;
}
.example-padding {
padding: var(--custom-padding);
}
</style>
<div class="example-padding">This element has padding defined by @property.</div>
Explanation: The --custom-padding
property defaults to 10px
, which can be overridden by its parent element.
Transitionable Properties
Custom properties defined with @property
can participate in transitions and animations.
<style>
@property --custom-bg {
syntax: '';
inherits: false;
initial-value: #007BFF;
}
.transition-example {
background-color: var(--custom-bg);
transition: background-color 0.5s ease;
}
.transition-example:hover {
--custom-bg: #FF5733;
}
</style>
<div class="transition-example">Hover to see the transition effect.</div>
Explanation: The custom property --custom-bg
transitions smoothly between colors when the element is hovered over.
Key Takeaways
- Enhanced Variables: The
@property
rule provides additional control over CSS variables. - Default Values: Set default values with the
initial-value
attribute. - Transitionable: Properties defined with
@property
can be animated and transitioned. - Type Enforcement: Use the
syntax
attribute to specify the expected type of the property value. - Inheritance: Control whether a property is inherited using the
inherits
attribute.