javajavafxjavafx-css

Can you dynamically apply a colour scheme to a single css file?


I have 4 different css files that are identical except they use different colour schemes i.e. red, blue, green. At the start of my program a user chooses which colour scheme they want and then the corresponding css file is chosen. Is there a way to just have 1 css file and have all colour schemes located in that file then when a user chooses a scheme have each item in the css file have the chosen colour applied to them?

I am using javaFX 8.


Solution

  • As A Haworth mentioned, you can probably do something with CSS variables. I don't know how javaFX works, but hopefully you can do something similar to what I wrote below. I set a CSS variable to the body and then have jQuery change that variable when the user clicks the buttons.

    $(document).ready(function() {
       $("body").on("click", "#blue", function() {
         $("body").css("--main-color", "blue");
       });
       $("body").on("click", "#red", function() {
         $("body").css("--main-color", "red");
       });
    });
    :body {
      --main-color: blue;
    }
    
    .div-1 {
      background: var(--main-color);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <div class="div-1">Div 1</div>
      <button id='blue'>Blue</button>
      <button id='red'>Red</button>
    </body>
    </html>