Functions in CSS
?? Functions in CSS
CSS functions are special notations used to perform calculations, manipulate colors, or control values dynamically. They are often used inside property values.
Common CSS Functions
| Function | Purpose | Example |
|---|---|---|
calc() | Performs calculations (add, subtract, multiply, divide) | width: calc(100% - 50px); |
var() | Uses CSS custom properties (variables) | color: var(--main-color); |
rgb(), rgba() | Defines colors using red-green-blue (with alpha) | color: rgba(255, 0, 0, 0.5); |
hsl(), hsla() | Defines colors using hue, saturation, lightness (with alpha) | color: hsl(120, 100%, 50%); |
url() | Links to external resources like images | background-image: url('image.png'); |
min(), max(), clamp() | Sets responsive or constrained values | width: clamp(300px, 50%, 600px); |
attr() | Retrieves attribute values (mostly in generated content) | content: attr(data-label); |
linear-gradient(), radial-gradient() | Creates gradient backgrounds | background: linear-gradient(to right, red, blue); |
Examples
1. calc() for dynamic sizing
.box { width: calc(100% - 40px); /* 100% container width minus 40px */ padding: 20px;}2. Using CSS Variables with var()
:root { --primary-color: #3498db;}button { background-color: var(--primary-color);}3. clamp() for responsive font size
h1 { font-size: clamp(1.5rem, 2vw, 3rem); /* Minimum 1.5rem, scales with viewport width, max 3rem */}4. Gradient Background
.header { background: linear-gradient(to right, #ff7e5f, #feb47b);}Why use CSS Functions?
Dynamic values: Adjust sizes or colors without manual recalculation.
Responsive design: Adapt to screen sizes smoothly.
Reusability: Variables simplify theme changes.
Better control: More precise control over styles.
Want examples or explanations of any specific CSS function?