learn react ui logoLearnReactUI
CSS Units

CSS Unit Sample

A React component demonstrating different CSS units (px, em, rem) with interactive controls to visualize how these units behave in relation to font sizes. This component provides a hands-on way to understand CSS unit behavior and their relationship with parent and root font sizes.

Demo

Features

  • Multiple Unit Support: Switch between px, em, and rem units
  • Dynamic Font Size Control: Adjust both HTML root and box element font sizes
  • Real-time Visualization: See how different units respond to font size changes
  • Interactive Controls: Sliders for font size adjustments and unit selection
  • Visual Feedback: Clear demonstration of unit behavior through a colored box

Example Usage

import CSSUnitSample from './CSSUnitSample';

// Basic usage
const App = () => {
  return (
    <CSSUnitSample 
      path="/path-to-demo" 
      title="CSS Units Demo" 
    />
  );
};

CSS Units Explained

The component demonstrates three main CSS units:

  • px (Pixels): Absolute unit that maintains a fixed size regardless of parent or root font sizes
  • em: Relative unit based on the parent element's font size
  • rem: Relative unit based on the root (html) element's font size

Interactive Controls

The component provides several controls to experiment with CSS units:

  1. HTML Font Size Slider: Adjusts the root font size (affects rem units)
  2. Box Font Size Slider: Adjusts the box element's font size (affects em units)
  3. Unit Selector: Switch between px, em, and rem units

Visual Demonstration

The component displays a colored box that changes size based on:

  • Selected unit type (px/em/rem)
  • Current HTML font size
  • Current box font size

Technologies Used

  • React: Component-based UI development
  • Emotion: CSS-in-JS styling solution
  • Ant Design: UI components including Select, Slider, and Typography
  • CSS Units: Demonstration of px, em, and rem units

Implementation Details

The component uses the following key features:

// Unit size calculation
const getSize = () => {
  switch (mode) {
    case 'em':
      return { edgeW: '8em', edgeH: '4em', fontS: `${boxFontSize}px` };
    case 'rem':
      return { edgeW: '8rem', edgeH: '4rem', fontS: `${boxFontSize}px` };
    default:
      return { edgeW: '128px', edgeH: '64px', fontS: `${boxFontSize}px` };
  }
};

// Dynamic HTML font size adjustment
React.useEffect(() => {
  const body = document.getElementsByTagName('html')[0];
  body.style.fontSize = `${htmlFontSize}px`;
}, [htmlFontSize]);

Getting Started

  1. Install dependencies:
npm install
  1. Run the development server:
npm run dev
  1. Open your browser and navigate to the provided local URL to see the demo in action.