Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <main>
   <h1>
      CSS Variable Customizer Template
   </h1>

   <p>
      Use the window in the bottom right to adjust this page's CSS variables. Made something and then experiment with the styling in real time.
   </p>
</main>

<div id="variable-changer"></div>
              
            
!

CSS

              
                :root {
   --backgroundColor: #fbfcf7;
   --maxWidth: 65ch;
   --font: "Georgia";
}

body {
   background-color: var(--backgroundColor);
   font-family: var(--font);
}

main {
   padding: 1rem;
   margin: 0 auto;
   max-width: var(--maxWidth);
}

              
            
!

JS

              
                // Change these!
const variables = [
   {
      name: "backgroundColor",
      label: "Background Color",
      type: "color"
   },
   {
      name: "maxWidth",
      label: "Max Width",
      type: "range",
      min: "50",
      max: "90",
      step: "1",
      unit: "ch"
   },
   {
      name: "font",
      label: "Font Family",
      type: "dropdown",
      options: ["Arial", "Georgia", "Futura", "Comic Sans MS"]
   }
];

// Reusable Logic
const getInitValue = (name, options = {}) => {
   const baseValue = window
      .getComputedStyle(document.body)
      .getPropertyValue(`--${name}`)
      .replace(" ", "");

   if (options.unit) {
      return baseValue.replace(options.unit, "");
   }

   return baseValue;
};
const updateStyleProp = (name, value) =>
   document.documentElement.style.setProperty(`--${name}`, value);

// Style Components
const { useRef, useState, useEffect, forwardRef, useImperativeMethods } = React;

const inputStyles = {
   position: "relative",
   width: "100%",
   minHeight: "25px",
   display: "flex",
   alignItems: "center",
   justifyContent: "space-between",
   gap: "1rem"
};

const ColorVariable = forwardRef(({ variable }, ref) => {
   const { name, label, type } = variable;

   const initValue = getInitValue(name);
   const [value, setValue] = useState(initValue);

   useEffect(() => {
      updateStyleProp(name, value);
   }, [value]);

   useImperativeMethods(ref, () => ({
      randomize: () => {
         const randomColorCode = () => {
            const characters = [
               "0",
               "1",
               "2",
               "3",
               "4",
               "5",
               "6",
               "7",
               "8",
               "9",
               "A",
               "B",
               "C",
               "D",
               "E",
               "F"
            ];
            const getRandomChar = () =>
               characters[Math.floor(Math.random() * characters.length)];

            return `#${getRandomChar()}${getRandomChar()}${getRandomChar()}${getRandomChar()}${getRandomChar()}${getRandomChar()}`;
         };
         setValue(randomColorCode());
      }
   }));

   return (
      <div style={inputStyles}>
         <label for={name}>{label}</label>
         <input
            id={name}
            name={name}
            type="color"
            onChange={(e) => {
               setValue(e.target.value);
            }}
            value={value}
         />
      </div>
   );
});

const NumberVariable = forwardRef(({ variable }, ref) => {
   const { name, label, type, min, max, step, unit } = variable;

   const initValue = getInitValue(name, { unit: unit });
   const [value, setValue] = useState(initValue);

   const rangeStyles = {
      display: "flex",
      flexDirection: "column",
      alignItems: "center",
      gap: "0.15rem"
   };

   const unitStyles = {
      fontSize: "0.65rem"
   };

   useEffect(() => {
      updateStyleProp(name, value + unit);
   }, [value]);

   useImperativeMethods(ref, () => ({
      randomize: () => {
         const randomWhole = Math.floor(
            Math.random() * (parseInt(max) - parseInt(min) + 1) + parseInt(min)
         );
         const randomInteger = () => {
            if (randomWhole === parseInt(max) || step === "1") {
               return 0;
            }

            const potentialSteps = Math.floor(1 / step) - 1;
            const numberOfSteps = Math.floor(
               Math.random() * (potentialSteps - parseInt(min) + 1) +
                  parseInt(min)
            );

            return numberOfSteps * step;
         };
         setValue(randomWhole + randomInteger());
      }
   }));

   return (
      <div style={{ ...inputStyles, alignItems: "flex-start" }}>
         <label for={name}>{label}</label>
         <span style={rangeStyles}>
            <input
               id={name}
               name={name}
               type="range"
               min={min}
               max={max}
               step={step}
               value={value}
               onChange={(e) => {
                  setValue(e.target.value);
               }}
            />
            <span style={unitStyles}>
               {value}
               {unit}
            </span>
         </span>
      </div>
   );
});

const DropdownVariable = forwardRef(({ variable }, ref) => {
   const { name, label, type, options } = variable;

   const initValue = getInitValue(name);
   const [value, setValue] = useState(initValue.replaceAll('"', ""));

   useEffect(() => {
      updateStyleProp(name, value.replaceAll('"', ""));
   }, [value]);

   useImperativeMethods(ref, () => ({
      randomize: () => {
         const randomOption =
            options[Math.floor(Math.random() * options.length)];
         setValue(randomOption);
      }
   }));

   return (
      <div style={inputStyles}>
         <label for={name}>{label}</label>
         <select
            name={name}
            id={name}
            value={value}
            onChange={(e) => setValue(e.target.value)}
         >
            {options.map((option) => {
               return (
                  <option
                     selected={option === value ? "true" : "false"}
                     key={option}
                     value={option}
                  >
                     {option}
                  </option>
               );
            })}
         </select>
      </div>
   );
});

// All Style Components
const VariableChanger = ({ variables }) => {
   const [containerHeight, setContainerHeight] = useState(0);
   const [expanded, setExpanded] = useState(true);
   const [numberRefs, setNumberRefs] = useState([]);
   const [variableComponents, setVariableComponents] = useState(
      variables.map((variable) => {
         if (variable.type === "color") {
            return <ColorVariable ref={useRef()} variable={variable} />;
         } else if (variable.type === "range") {
            return <NumberVariable ref={useRef()} variable={variable} />;
         } else if (variable.type === "dropdown") {
            return <DropdownVariable ref={useRef()} variable={variable} />;
         }
      })
   );

   useEffect(() => {
      const containerHeight = this.container.clientHeight;
      setContainerHeight(containerHeight);
   }, []);

   const containerStyles = {
      position: "fixed",
      bottom: expanded ? 0 : (containerHeight + 2) * -1,
      right: "1rem",
      zIndex: 999,

      color: "black",
      padding: "0.75rem 1rem",
      fontFamily: "Arial, sans-serif",

      backgroundColor: "#ffffff",
      border: "2px solid black",
      borderBottomWidth: "0px",
      borderTopLeftRadius: "0.5rem"
   };

   const formStyles = {
      display: "flex",
      flexDirection: "column",
      gap: "0.75rem",

      fontSize: "0.8rem"
   };

   const buttonStyles = {
      position: "absolute",
      bottom: "100%",
      right: "-2px",
      padding: "0.25rem 0.75rem",

      fontSize: "0.8rem",

      backgroundColor: "#ddddee",
      border: "2px solid black",
      borderBottomWidth: "0px",
      borderTopRightRadius: "0.5rem",
      borderTopLeftRadius: "0.5rem",

      cursor: "pointer",
      "&:hover, &:focus": {
         outline: "2px solid blue",
         outlineOffset: "4px"
      }
   };

   const randomizeVariables = (e) => {
      e.preventDefault();
      variableComponents.forEach((component) =>
         component.ref.current.randomize()
      );
   };

   return (
      <div
         ref={(container) => {
            this.container = container;
         }}
         aria-expanded={expanded}
         style={containerStyles}
      >
         <button onClick={() => setExpanded(!expanded)} style={buttonStyles}>
            {expanded ? "Hide" : "Show"} Styles
         </button>
         <form style={formStyles}>
            {variableComponents.map((component) => component)}

            <button onClick={(e) => randomizeVariables(e)}>Randomize!</button>
         </form>
      </div>
   );
};

// Add to the DOM
ReactDOM.render(
   <VariableChanger variables={variables} />,
   document.getElementById("variable-changer")
);

              
            
!
999px

Console