- Using CSS custom properties (variables)
- Basic usage
- First steps with custom properties
- Using the :root pseudo-class
- Inheritance of custom properties
- Custom property fallback values
- Handling invalid custom properties
- Invalid normal properties
- HTML
- Javascript – Is it possible to pass parameters to css file?
- Best Solution
- 1.2 What is Fingerprinting and Why Should I Care?
- Related Solutions
Using CSS custom properties (variables)
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., —main-color: black; ) and are accessed using the var() function (e.g., color: var(—main-color); ).
Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, —main-text-color is easier to understand than #00ff00 , especially if this same color is also used in other contexts.
Custom properties are subject to the cascade and inherit their value from their parent.
Note: Variables do not work inside media queries and container queries. The var() function can be used in place of any part of a value in any property on an element. The var() function cannot be used as property names, selectors, or anything else besides property values. So, we can’t use it in a media query or container query.
Basic usage
Declaring a custom property is done using a custom property name that begins with a double hyphen ( — ), and a property value that can be any valid CSS value. Like any other property, this is written inside a ruleset, like so:
element --main-bg-color: brown; >
Note that the selector given to the ruleset defines the scope that the custom property can be used in. A common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your HTML document:
However, this doesn’t always have to be the case: you maybe have a good reason for limiting the scope of your custom properties.
Note: Custom property names are case sensitive — —my-color will be treated as a separate custom property to —My-color .
As mentioned earlier, you use the custom property value by specifying your custom property name inside the var() function, in place of a regular property value:
element background-color: var(--main-bg-color); >
First steps with custom properties
Let’s start with this CSS that applies the same color to elements of different classes:
.one color: white; background-color: brown; margin: 10px; width: 50px; height: 50px; display: inline-block; > .two color: white; background-color: black; margin: 10px; width: 150px; height: 70px; display: inline-block; > .three color: white; background-color: brown; margin: 10px; width: 75px; > .four color: white; background-color: brown; margin: 10px; width: 100px; > .five background-color: brown; >
We’ll apply it to this HTML:
div> div class="one">1:div> div class="two">2: Text span class="five">5 - more textspan>div> input class="three" /> textarea class="four">4: Lorem Ipsumtextarea> div>
This produces the following result:
Using the :root pseudo-class
Notice the repetitive CSS in the example above. The background color is set to brown in several places. For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally. For non-trivial projects, this is not always possible. By declaring a custom property on the :root pseudo-class and using it where needed throughout the document, a CSS author can reduce the need for repetition:
:root --main-bg-color: brown; > .one color: white; background-color: var(--main-bg-color); margin: 10px; width: 50px; height: 50px; display: inline-block; > .two color: white; background-color: black; margin: 10px; width: 150px; height: 70px; display: inline-block; > .three color: white; background-color: var(--main-bg-color); margin: 10px; width: 75px; > .four color: white; background-color: var(--main-bg-color); margin: 10px; width: 100px; > .five background-color: var(--main-bg-color); >
div> div class="one">div> div class="two">Text span class="five">- more textspan>div> input class="three" /> textarea class="four">Lorem Ipsumtextarea> div>
This leads to the same result as the previous example, yet allows for one canonical declaration of the desired property value; very useful if you want to change the value across the entire page later.
Inheritance of custom properties
Custom properties do inherit. This means that if no value is set for a custom property on a given element, the value of its parent is used. Take this HTML:
div class="one"> div class="two"> div class="three">div> div class="four">div> div> div>
.two --test: 10px; > .three --test: 2em; >
In this case, the results of var(—test) are:
- For the class=»two» element: 10px
- For the class=»three» element: 2em
- For the class=»four» element: 10px (inherited from its parent)
- For the class=»one» element: invalid value, which is the default value of any custom property
Keep in mind that these are custom properties, not actual variables like you might find in other programming languages. The value is computed where it is needed, not stored for use in other rules. For instance, you cannot set a property for an element and expect to retrieve it in a sibling’s descendant’s rule. The property is only set for the matching selector and its descendants, like any normal CSS.
Custom property fallback values
Using the var() function, you can define multiple fallback values when the given variable is not yet defined; this can be useful when working with Custom Elements and Shadow DOM.
Note: Fallback values aren’t used to fix the browser compatibility. If the browser doesn’t support CSS custom properties, the fallback value won’t help. It’s just a backup for the browser which supports CSS custom properties to choose a different value if the given variable isn’t defined or has an invalid value.
The first argument to the function is the name of the custom property to be substituted. The second argument to the function, if provided, is a fallback value, which is used as the substitution value when the referenced custom property is invalid. The function only accepts two parameters, assigning everything following the first comma as the second parameter. If that second parameter is invalid, the fallback will fail. For example:
.two /* Red if --my-var is not defined */ color: var(--my-var, red); > .three /* pink if --my-var and --my-background are not defined */ background-color: var(--my-var, var(--my-background, pink)); > .three /* Invalid: "--my-background, pink" */ background-color: var(--my-var, --my-background, pink); >
Including a custom property as a fallback, as seen in the second example above, is the correct way to provide more than one fallback. The technique has been seen to cause performance issues as it takes more time to parse through the variables.
Note: The syntax of the fallback, like that of custom properties, allows commas. For example, var(—foo, red, blue) defines a fallback of red, blue — anything between the first comma and the end of the function is considered a fallback value.
Handling invalid custom properties
Each CSS property can be assigned a defined set of values. If you try to assign a value to a property that is outside its set of valid values, it’s considered invalid.
When the browser encounters an invalid value for a normal property, it discards the value, and elements are assigned the values that they would have had if the declaration simply did not exist.
However, when the values of custom properties are parsed, the browser doesn’t yet know where they will be used, so it must consider nearly all values as valid.
Unfortunately, these valid values can be used, via the var() functional notation, in a context where they might not make sense. Properties and custom variables can lead to invalid CSS statements, leading to the new concept of valid at computed time.
When the browser encounters an invalid var() substitution, then the initial or inherited value of the property is used.
The next two examples illustrate this.
Invalid normal properties
In this example we attempt to apply a value of 16px to the color property. Because this is invalid, the CSS is discarded and the result is as if the rule did not exist, so the previous color: blue rule is applied instead, and the paragraph is blue.
HTML
p>This paragraph is initially black.p>
Javascript – Is it possible to pass parameters to css file?
What does this mean? Is it like passing a param or a suffix to the filename?
Best Solution
It is not, at least in this context, passing details to the CSS. Generally that’s a means of ensuring a browser’s cache can be busted by the CSS provier when assets are being concat’d or minified. using my.css?somestringofnumber is also generally considered inferior to using a unique filename, for example my-12312341234.css but both methods are used widely.
Note the asset pipeline guide on fingerprinting for Rails:
1.2 What is Fingerprinting and Why Should I Care?
Fingerprinting is a technique that makes the name of a file dependent on the contents of the file. When the file contents change, the filename is also changed. For content that is static or infrequently changed, this provides an easy way to tell whether two versions of a file are identical, even across different servers or deployment dates.
When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment, or in web browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change. This will cause the remote clients to request a new copy of the content. This is generally known as cache busting.
And on the query string method:
- Not all caches will reliably cache content where the filename only differs by query parameters: Steve Souders recommends, «. avoiding a querystring for cacheable resources». He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation.
- The file name can change between nodes in multi-server environments: [. ] When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request.
- Too much cache invalidation: When static assets are deployed with each new release of code, the mtime (time of last modification) of all these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed.
Related Solutions
Html – Set cellpadding and cellspacing in CSS
For controlling «cellpadding» in CSS, you can simply use padding on table cells. E.g. for 10px of «cellpadding»:
For «cellspacing», you can apply the border-spacing CSS property to your table. E.g. for 10px of «cellspacing»:
This property will even allow separate horizontal and vertical spacing, something you couldn’t do with old-school «cellspacing».
Issues in IE ≤ 7
This will work in almost all popular browsers except for Internet Explorer up through Internet Explorer 7, where you’re almost out of luck. I say «almost» because these browsers still support the border-collapse property, which merges the borders of adjoining table cells. If you’re trying to eliminate cellspacing (that is, cellspacing=»0″ ) then border-collapse:collapse should have the same effect: no space between table cells. This support is buggy, though, as it does not override an existing cellspacing HTML attribute on the table element.
In short: for non-Internet Explorer 5-7 browsers, border-spacing handles you. For Internet Explorer, if your situation is just right (you want 0 cellspacing and your table doesn’t have it defined already), you can use border-collapse:collapse .
Note: For a great overview of CSS properties that one can apply to tables and for which browsers, see this fantastic Quirksmode page.
Html – How to align content of a div to the bottom
Relative+absolute positioning is your best bet:
#header < position: relative; min-height: 150px; >#header-content < position: absolute; bottom: 0; left: 0; >#header, #header *
But you may run into issues with that. When I tried it I had problems with dropdown menus appearing below the content. It’s just not pretty.
Honestly, for vertical centering issues and, well, any vertical alignment issues with the items aren’t fixed height, it’s easier just to use tables.