Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS Variables on Stripe Elements

I am using Stripe Elements for a credit card checkout. The issue is, that I am not able (or I simply don't know how) to use my own CSS variables on this Stripe Element. I need to use CSS variables for the sake of changing colors when the user changes the theme. Here is my current implementation:

Variable definitions (I'm using SASS)

.theme1
    --color-1: red
    --color-2: pink
    // ...
.theme2
    --color-1: blue
    --color-2: lilec
    // ...
.theme3
    --color-1: orange
    --color-2: yellow
    // ...
// ...

The CSS variables are defined under the scope of a class, that is put to the body depending which theme is currently selected.

HTML (I am using Angular 6)

<div #stripe></div>

Typescript

    @ViewChild('stripe') el: ElementRef;
    card: any;
    cardHandler = this.onChange.bind(this);
    async onSubmit() { /* ... */ }

    setupStripe(): void {
        this.card = stripeElements.create('card', {
            iconStyle: 'solid',
            style: {
                base: {
                    iconColor: 'var(--some-var)',
                    // using css variables here does not work
                    // ...
                },
            }
        });
        this.card.mount(this.el.nativeElement);
        this.card.addEventListener('change', this.cardHandler);
    }
    destroyStripe(): void {
        this.card.removeEventListener('change', this.cardHandler);
        this.card.destroy();
    }

    ngAfterViewInit() {
        this.setupStripe();
    }

    ngOnDestroy() {
        this.destroyStripe();
    }

    onChange({ error }) { /* ... */ }

Styles (I am using SASS)

.StripeElement
    background-color: var(--dy-bg-1)
    // I don't have access to font colors etc here
    color: var(--dy-txt-1) !important
    // !important also does not work

P.S.: It's important for me, that the variables will change at runtime (which is the reason I'm using CSS variables.

like image 911
Flo Avatar asked Oct 29 '25 03:10

Flo


1 Answers

The Stripe documentation says

Elements creates UI components for you that are hosted by Stripe

i.e. their input fields are in a different document, so don't have access to your custom CSS variables.

A 'good enough' solution might be to read the CSS Custom Property values in your setupStripe method, and pass the values over as plain strings:

// Note: document.body is just an example:
const styles = getComputedStyle(document.body);
this.card = stripeElements.create("card", {
  iconStyle: "solid",
  style: {
    base: {
      iconColor: styles.getPropertyValue("--some-var")
      // ...etc
    }
  }
});
like image 82
searlea Avatar answered Oct 31 '25 16:10

searlea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!