fix(css-vars): nullish v-bind in style should not lead to unexpected inheritance
- Fixes #12434
- Fixes #12439
- Fixes #7474
- Close #7475
Currently, we generate CSS custom properties on component roots for each v-bind in SFC <style> blocks. When one component instance is nested inside another, the nested instance can inherit values from the outer instance, even if its own binding value is undefined or null. Ideally, style bindings should be scoped per component instance since they depend on the instance's state. However, with the current approach using CSS custom properties, we can't generate unique hashed names for each instance because CSS can only reference a single property.
To address this, the improvement here is to "reset" these custom properties when the binding value is nullish.
Current Behavior:
- In SSR, we ignore nullish values.
- In CSR, we generate
--<hash>-<name>:undefinedforundefinedbut ignorenull, which causes inconsistencies and is related to the hydration warning in #12439.
This PR:
- Ensures both CSR and SSR generate
--<hash>-<name>:initialfor nullish values. This properly resets the custom property, as explained in the CSS spec. It behaves as if no custom property is defined in ancestor elements.
SSR Note:
- Added a special
:prefix to distinguish style entries coming fromv-bindin styles. This allows us to process them separately from user-defined custom properties inssrRenderStyle. Alternatively, we can also create a new runtime helper and modify the codegen here:
Not sure if my current approach is preferred. Let me know if you have other opinions.
Summary by CodeRabbit
-
New Features
- Introduced a utility to normalize CSS variable values, ensuring consistent and safe handling of CSS custom properties.
- Added new test cases to verify correct behavior when CSS variables are set to
null,undefined, or invalid values.
-
Bug Fixes
- CSS variables with
nullorundefinedvalues now default to'initial'to prevent unintended inheritance. - Improved handling of CSS variable keys and values during server-side rendering and hydration.
- CSS variables with
-
Refactor
- Updated internal type definitions to allow more flexible CSS variable value types.
-
Documentation
- Enhanced code comments explaining the rationale behind CSS variable key formatting changes.
-
Chores
- Expanded public exports to include new CSS variable utilities.
Size Report
Bundles
| File | Size | Gzip | Brotli |
|---|---|---|---|
| runtime-dom.global.prod.js | 101 kB (+74 B) | 38.4 kB (+31 B) | 34.5 kB (+27 B) |
| vue.global.prod.js | 159 kB (+74 B) | 58.5 kB (+29 B) | 52.1 kB (+139 B) |
Usages
| Name | Size | Gzip | Brotli |
|---|---|---|---|
| createApp (CAPI only) | 46.5 kB | 18.2 kB | 16.7 kB |
| createApp | 54.5 kB | 21.2 kB | 19.4 kB |
| createSSRApp | 58.7 kB | 22.9 kB | 20.9 kB |
| defineCustomElement | 59.4 kB | 22.8 kB | 20.8 kB |
| overall | 68.5 kB | 26.4 kB | 24 kB |
@vue/compiler-core
npm i https://pkg.pr.new/@vue/compiler-core@12461
@vue/compiler-dom
npm i https://pkg.pr.new/@vue/compiler-dom@12461
@vue/compiler-sfc
npm i https://pkg.pr.new/@vue/compiler-sfc@12461
@vue/compiler-ssr
npm i https://pkg.pr.new/@vue/compiler-ssr@12461
@vue/reactivity
npm i https://pkg.pr.new/@vue/reactivity@12461
@vue/runtime-core
npm i https://pkg.pr.new/@vue/runtime-core@12461
@vue/runtime-dom
npm i https://pkg.pr.new/@vue/runtime-dom@12461
@vue/server-renderer
npm i https://pkg.pr.new/@vue/server-renderer@12461
@vue/shared
npm i https://pkg.pr.new/@vue/shared@12461
vue
npm i https://pkg.pr.new/vue@12461
@vue/compat
npm i https://pkg.pr.new/@vue/compat@12461
commit: 582db40
I think this would also close #7474 and the associated PR #7475.
There's an underlying question here about whether we consider undefined and null to be valid values for CSS v-bind(). Should we support them, or should we just log a warning? It is possible to handle them in userland code instead, e.g. using v-bind(c ?? 'initial').
Then there's a follow up decision about where to draw the line. What about an empty string (Playground)? Or a white-space value like " "? Or an empty array (Playground)? Etc.
I don't want to expand the scope of this PR unnecessarily, but I do think it's important to be clear why we're drawing the line at nullish values.
@skirtles-code Thanks for the feedback! Great questions!
Here’s what I thought:
- Why not handle them in userland?
Theoretically, using CSS custom properties for
v-bindin<style>blocks is an implementation detail that users are not supposed to be aware of. However, there are notable differences in behavior betweencolor: v-bind('"initial"')andcolor: initial. The former bindsinitialto the custom property, making it functionally equivalent tocolor: unset, whereas the latter directly applies theinitialkeyword as intended in CSS. Making users to writeinitialto reset values while it actually behaves likeunsetcan be quite frustrating, so I would prefer to make it more transparent. - Why only convert nullish values?
You're absolutely right—more values should be considered. I think it's kind of similar to our props coercion, where we are removing a binding with nullish values. For CSS custom properties, "removing" in this context means resetting to their initial value, which is the guaranteed invalid value, which can be explicitly set with the keyword
initial. ~~Per the CSS specification, empty strings and white spaces for custom properties behave differently frominitial, as they prevent fallback values from taking effect. Currently, we are removing the custom property for empty strings, but retaining white spaces. This creates an inconsistency if users are binding the value to a custom property themselves (Playground).~~ ~~To address this, I believe we should treat empty strings and white spaces as-is, maintaining consistency and aligning better with user expectations. I reconsidered and think we should handle it comprehensively as outlined in the table below. Could you kindly help review it? Thank you!~~
The situation is more complicated than I expected. I'm investigating the current behavior of Vue and CSS custom properties.
Current behavior:
v-bind value |
SSR output | CSR output | Mismatch |
|---|---|---|---|
null |
/ | / | |
undefined |
/ | --foo: undefined |
⚠️ |
| empty string | --foo:; |
/ | ⚠️ |
| white spaces | --foo: ; |
--foo: ; |
For Vue, undefined and empty string will cause SSR/CSR mismatch
For CSS custom properties:
- The
cssText, code in<style>, andstyleattribute behave differently fromstyle.setProperty. During SSR, we use the former, while during CSR, we use both. - The behavior of
--foo:;differs fromstyle.setProperty('--foo', ''). The former acts like white spaces, while the latter effectively removes the declaration.
Since we are binding values to CSS, we should align with CSS behavior, where an empty string is treated as equivalent to white spaces. To fix the SSR/CSR mismatch and ensure consistent resetting, I propose handling values as follows:
v-bind value |
SSR | CSR |
|---|---|---|
null |
--foo: initial |
style.setProperty('--foo', 'initial') |
undefined |
--foo: initial |
style.setProperty('--foo', 'initial') |
| empty string | --foo: ; |
style.setProperty('--foo', ' ') |
| white spaces | --foo: ; |
style.setProperty('--foo', ' ') |
For other string values, we should output them as-is. For unsupported types of values, we should warn about the binding and retain the current behavior (rendering everything as a string, likely using String(value)).
WDYT? /cc @adamdehaven @skirtles-code @edison1105
@Justineo I thought we determined that a whitespace character would be ideal?
After rereading the spec, I believe that only the initial value truly resets the custom property to its default state, as if it were never set.
After rereading the spec, I believe that only the
initialvalue truly resets the custom property to its default state, as if it were never set.
The white space character seems to work in practice if you can try?
The white space character seems to work in practice if you can try?
White space sets a valid empty value, which will prevent fallback value to take effect. initial resets the custom property to its initial value–the guaranteed invalid value, which is the same as it’s not declared. I have tested and can confirm the implementation is aligned with the spec in all major browsers.
The white space character seems to work in practice if you can try?
White space sets a valid empty value, which will prevent fallback value to take effect.
initialresets the custom property to its initial value–the guaranteed invalid value, which is the same as it’s not declared. I have tested and can confirm the implementation is aligned with the spec in all major browsers.
I'm not sure injecting initial in all those places though is desirable. Do you have a reproduction with this behavior?
In my testing, initial and a white space character behave differently.
See the example taken from here
I'm not sure injecting
initialin all those places though is desirable.
It is the standard way to reset a custom property.
Do you have a reproduction with this behavior?
https://codepen.io/Justineo/pen/VYZZPOz
As shown in this pen, initial works the same as not setting the value.
In my testing,
initialand a white space character behave differently.
That’s why we should use initial instead of white spaces…
See the example taken from here
We certainly don’t want to invalidate the fallback value red in var(--foo, red) when no valid value is bound to --foo. Therefore, using initial is the only appropriate solution.
https://codepen.io/Justineo/pen/VYZZPOz
The reproduction looks correct; thanks for putting that together
TLDR: I think the latest proposal looks good.
I wasn't initially clear about the difference between initial and v-bind('"initial"'), so I put together a Playground to help demonstrate:
v-bind('"initial"') does indeed behave like unset, not initial. I concur that this does make handling undefined/null in userland less appealing.
Using initial for undefined and null makes sense to me.
I also like the idea of treating an empty string as a space. That prevents the variable being inherited from the parent component and also seems consistent with vanilla CSS. It wasn't immediately clear to me why a space character would be better than initial in that case, so I put together another Playground to show an example where it would actually make a difference:
In that example, we would want v-bind('""') to behave like .bar and .baz, not .foo, so a space character seems to give us what we want.
@skirtles-code Thank you for the demos! I’ll update the code to align with our latest conclusions.
@edison1105 is there anything else myself or @Justineo can provide here to help this PR along?
I have a workaround in my project in a draft PR; however, it's definitely "messy" requiring me to manually inject initial all over the place in my userland code.
@adamdehaven I've approved this PR. then, we need to wait for Evan's review. It should be included in the next release.
@yyx990803 Please review this PR.
Walkthrough
This change introduces a new utility, normalizeCssVarValue, to standardize and sanitize CSS variable values across both client and server code paths. It updates the handling of CSS variables in SSR and runtime, ensuring that null or undefined values are reset to 'initial' and that invalid values emit warnings. Test cases are added and updated to verify these behaviors.
Changes
| File(s) | Change Summary |
|---|---|
packages/shared/src/cssVars.ts, packages/shared/src/index.ts |
Added normalizeCssVarValue utility and exported it. |
packages/shared/__tests__/cssVars.spec.ts |
Added tests for normalizeCssVarValue, including value normalization and warning emission. |
packages/runtime-dom/src/helpers/useCssVars.ts |
Updated to use normalizeCssVarValue for all CSS vars; type signatures now allow unknown values. |
packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts |
Added test to confirm null/undefined CSS vars are set to 'initial'. |
packages/compiler-sfc/src/style/cssVars.ts, packages/compiler-sfc/__tests__/compileScript.spec.ts |
Changed SSR CSS var key prefix to :-- and updated related test expectations. |
packages/runtime-core/src/component.ts |
Relaxed type annotations for CSS vars from string to unknown. |
packages/runtime-core/src/hydration.ts |
Used normalizeCssVarValue for hydration CSS var comparison. |
packages/server-renderer/src/helpers/ssrRenderAttrs.ts, packages/server-renderer/__tests__/ssrRenderAttrs.spec.ts |
Added SSR-side normalization and reset logic for CSS vars with :-- prefix; added corresponding tests. |
Sequence Diagram(s)
sequenceDiagram
participant Component
participant useCssVars
participant normalizeCssVarValue
participant DOM
Component->>useCssVars: Provide state for CSS vars
useCssVars->>normalizeCssVarValue: Normalize each var value
normalizeCssVarValue-->>useCssVars: Return normalized value
useCssVars->>DOM: Set style property with normalized value
sequenceDiagram
participant SSRCompiler
participant ssrRenderStyle
participant normalizeCssVarValue
participant OutputHTML
SSRCompiler->>ssrRenderStyle: Pass style object with :-- keys
ssrRenderStyle->>normalizeCssVarValue: Normalize :-- var values
normalizeCssVarValue-->>ssrRenderStyle: Return normalized value
ssrRenderStyle->>OutputHTML: Output style attribute with normalized vars
Assessment against linked issues
| Objective | Addressed | Explanation |
|---|---|---|
Prevent parent CSS variable inheritance in nested components when using v-bind() in CSS (#12434) |
✅ | |
Avoid SSR hydration errors when combining inline styles with v-bind() in CSS (#12439) |
✅ | |
Do not add custom properties to style attribute when value is undefined or null (#7474, #7475) |
✅ |
Poem
🐇
A bunny with code in its fur,
Tidied CSS vars—no more blur!
Withnormalizein paw,
It hopped through each flaw,
Nownullmeans 'initial', for sure!"From SSR to DOM,
CSS chaos is calm!"
📜 Recent review details
Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 8ac9f6b0001dcd97907a09d90630f351cdac449a and 582db40af001b69c3e4935ac7ee26b7bf320c4b2.
⛔ Files ignored due to path filters (1)
packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (3)
packages/compiler-sfc/__tests__/compileScript.spec.ts(1 hunks)packages/runtime-core/src/component.ts(1 hunks)packages/runtime-core/src/hydration.ts(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/runtime-core/src/hydration.ts
- packages/runtime-core/src/component.ts
- packages/compiler-sfc/tests/compileScript.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: test / e2e-test
✨ Finishing Touches
- [ ] 📝 Generate Docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
🪧 Tips
Chat
There are 3 ways to chat with CodeRabbit:
- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
I pushed a fix in commit <commit_id>, please review it.Explain this complex logic.Open a follow-up GitHub issue for this discussion.
- Files and specific lines of code (under the "Files changed" tab): Tag
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai explain this code block.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.@coderabbitai read src/utils.ts and explain its main purpose.@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.@coderabbitai help me debug CodeRabbit configuration file.
Support
Need help? Create a ticket on our support page for assistance with any issues or questions.
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.
CodeRabbit Commands (Invoked using PR comments)
@coderabbitai pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile to the root of your repository. - Please see the configuration documentation for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation:
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
Documentation and Community
- Visit our Documentation for detailed information on how to use CodeRabbit.
- Join our Discord Community to get help, request features, and share feedback.
- Follow us on X/Twitter for updates and announcements.
/ecosystem-ci run
📝 Ran ecosystem CI: Open
| suite | result | latest scheduled |
|---|---|---|
| pinia | :white_check_mark: success | :white_check_mark: success |
| language-tools | :x: failure | :white_check_mark: success |
| primevue | :white_check_mark: success | :white_check_mark: success |
| quasar | :white_check_mark: success | :white_check_mark: success |
| test-utils | :white_check_mark: success | :white_check_mark: success |
| vite-plugin-vue | :white_check_mark: success | :white_check_mark: success |
| router | :white_check_mark: success | :white_check_mark: success |
| radix-vue | :white_check_mark: success | :white_check_mark: success |
| vant | :white_check_mark: success | :white_check_mark: success |
| vue-macros | :white_check_mark: success | :x: failure |
| vitepress | :white_check_mark: success | :white_check_mark: success |
| nuxt | :white_check_mark: success | :white_check_mark: success |
| vueuse | :white_check_mark: success | :white_check_mark: success |
| vue-simple-compiler | :white_check_mark: success | :white_check_mark: success |
| vue-i18n | :white_check_mark: success | :white_check_mark: success |
| vuetify | :white_check_mark: success | :white_check_mark: success |