Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <div id="root"></div>
              
            
!

CSS

              
                
              
            
!

JS

              
                // Helper functions
const hexToRgb = (hex) => {
  const bigint = parseInt(hex.slice(1), 16);
  return {
    r: (bigint >> 16) & 255,
    g: (bigint >> 8) & 255,
    b: bigint & 255
  };
};

const calculateLuminance = (r, g, b) => {
  const a = [r, g, b].map(v => {
    v /= 255;
    return v <= 0.03928
      ? v / 12.92
      : Math.pow((v + 0.055) / 1.055, 2.4);
  });
  return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
};

const calculateContrastRatio = (bg, fg, opacity) => {
  const bgRgb = hexToRgb(bg);
  const fgRgb = hexToRgb(fg);

  const blendedRgb = {
    r: fgRgb.r * opacity + bgRgb.r * (1 - opacity),
    g: fgRgb.g * opacity + bgRgb.g * (1 - opacity),
    b: fgRgb.b * opacity + bgRgb.b * (1 - opacity)
  };

  const bgLuminance = calculateLuminance(bgRgb.r, bgRgb.g, bgRgb.b);
  const fgLuminance = calculateLuminance(blendedRgb.r, blendedRgb.g, blendedRgb.b);

  const ratio = (Math.max(bgLuminance, fgLuminance) + 0.05) /
                (Math.min(bgLuminance, fgLuminance) + 0.05);

  return ratio.toFixed(2);
};

const formatContrastRatio = (ratio) => {
  const parts = ratio.split('.');
  const integerPart = parseInt(parts[0], 10).toString();
  const decimalPart = (parts[1] || '00').substring(0, 2);
  return `${integerPart}.${decimalPart}:1`;
};

// Block component
const Block = ({ backgroundColor, squareOpacity, squareColor, onBackgroundChange, darkMode }) => {
  const squareColorWithOpacity = `rgba(${parseInt(squareColor.slice(1, 3), 16)}, ${parseInt(squareColor.slice(3, 5), 16)}, ${parseInt(squareColor.slice(5, 7), 16)}, ${squareOpacity})`;
  const contrastRatio = calculateContrastRatio(backgroundColor, squareColor, squareOpacity);
  const formattedContrastRatio = formatContrastRatio(contrastRatio);

  return (
    <div style={{ flexGrow: 1, minWidth: '120px', margin: '8px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontFamily: 'system-ui' }}>
      <div style={{ fontWeight: 'bold', marginBottom: '8px' }}>{formattedContrastRatio}</div>
      <div 
        style={{ 
          width: '100%', 
          height: '150px', 
          backgroundColor, 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center',
          borderRadius: '12px' 
        }}
      >
        <div 
          style={{ 
            width: '50px', 
            height: '50px', 
            backgroundColor: squareColorWithOpacity, 
            borderRadius: '10px'
          }}
        ></div>
      </div>
      <input
        type="text"
        value={backgroundColor}
        onChange={(e) => onBackgroundChange(e.target.value)}
        style={{ 
          marginTop: '8px', 
          width: '70px', 
          textAlign: 'center', 
          border: '1px solid #ccc', 
          padding: '5px', 
          borderRadius: '8px',
          backgroundColor: darkMode ? '#282828' : '#FFFFFF',
          color: darkMode ? '#FFFFFF' : '#000000'
        }}
      />
    </div>
  );
};

// Main component
const ImprovedWCAGContrastDemoHex = () => {
  const [darkMode, setDarkMode] = React.useState(false);
  const [backgrounds, setBackgrounds] = React.useState([
    '#FFFFFF', '#EBEBEB', '#DDDDDD', '#C8C8C8', '#B4B4B4'
  ]);
  const [squareOpacity, setSquareOpacity] = React.useState(0.08);
  const [squareColor, setSquareColor] = React.useState('#000000');

  const darkModeBackgrounds = ['#1C1C1C', '#232323', '#282828', '#2E2E2E', '#343434'];
  
  const handleBackgroundChange = (index, color) => {
    const newBackgrounds = [...backgrounds];
    newBackgrounds[index] = color.startsWith('#') ? color : `#${color}`;
    setBackgrounds(newBackgrounds);
  };

  const handleSquareColorChange = (color) => {
    if (/^#[0-9A-F]{6}$/i.test(color)) {
      setSquareColor(color);
    }
  };

  const toggleTheme = () => {
    setDarkMode(!darkMode);
    if (!darkMode) {
      setBackgrounds(darkModeBackgrounds);
      setSquareColor('#FFFFFF');
    } else {
      setBackgrounds(['#FFFFFF', '#EBEBEB', '#DDDDDD', '#C8C8C8', '#B4B4B4']);
      setSquareColor('#000000');
    }
  };

  return (
    <div style={{ padding: '20px', backgroundColor: darkMode ? '#161616' : '#FFFFFF', color: darkMode ? '#FFFFFF' : '#000000', fontFamily: 'system-ui', maxWidth: '800px', margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: '20px' }}>
        <h1 style={{ fontSize: '24px', fontWeight: 'bold' }}>
          Opacity Contrast Ratio Demo
        </h1>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <label style={{ marginRight: '10px', fontWeight: 'bold' }}>Square color</label>
          <input
            type="text"
            value={squareColor}
            onChange={(e) => handleSquareColorChange(e.target.value)}
            style={{ 
              width: '100px', 
              textAlign: 'center', 
              border: '1px solid #ccc', 
              padding: '5px', 
              borderRadius: '8px', 
              backgroundColor: darkMode ? '#282828' : '#FFFFFF',
              color: darkMode ? '#FFFFFF' : '#000000'
            }}
          />
        </div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <label style={{ marginRight: '10px', fontWeight: 'bold' }}>Opacity level</label>
          <input
            type="range"
            min="0"
            max="1"
            step="0.01"
            value={squareOpacity}
            onChange={(e) => setSquareOpacity(parseFloat(e.target.value))}
            style={{ 
              marginRight: '10px', 
              width: '150px',
              backgroundColor: darkMode ? '#555555' : '#DDDDDD',
              color: darkMode ? '#FFFFFF' : '#000000'
            }}
          />
          <div>{(squareOpacity * 100).toFixed(0)}%</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <label style={{ marginRight: '10px', fontWeight: 'bold' }}>Dark mode</label>
          <input 
            type="checkbox" 
            checked={darkMode} 
            onChange={toggleTheme} 
            style={{ transform: 'scale(1.2)' }} 
          />
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-around', flexWrap: 'wrap', gap: '8px' }}>
        {backgrounds.map((bg, index) => (
          <Block
            key={index}
            backgroundColor={bg}
            squareOpacity={squareOpacity}
            squareColor={squareColor}
            onBackgroundChange={(color) => handleBackgroundChange(index, color)}
            darkMode={darkMode}
          />
        ))}
      </div>
    </div>
  );
};

// Render the component to the DOM
ReactDOM.render(<ImprovedWCAGContrastDemoHex />, document.getElementById('root'));
              
            
!
999px

Console