ctrl-center
v1.0.3
Published
The ultimate, production-ready solution for centering divs. Supports all frameworks, browsers, and edge cases.
Downloads
3
Maintainers
Readme
ctrl-center
The ultimate, production-ready solution for centering divs across all frameworks and browsers.
Finally, an npm package that solves the hardest problem in CSS: centering a div. But this isn't just another meme package—this is a comprehensive, enterprise-grade solution with framework support, accessibility features, and extensive testing.
✨ Features
- 🎯 Multiple centering methods - Grid, Flexbox, Absolute, Text, and more
- 🌐 Framework agnostic - Works with React, Vue, Angular, and vanilla HTML
- 📱 Responsive design - Container queries and viewport-aware centering
- ♿ Accessibility first - WCAG compliant with reduced motion support
- 🌍 RTL support - Full right-to-left language compatibility
- ⚡ Performance optimized - GPU acceleration and containment optimizations
- 🔧 Developer friendly - TypeScript definitions and comprehensive tooling
- 🛡️ Production ready - Extensive testing and conflict detection
🚀 Quick Start
Installation
# npm
npm install ctrl-center
# yarn
yarn add ctrl-center
# pnpm
pnpm add ctrl-center🎬 Demos
Try the package as an npm dependency via local demos powered by Vite.
React (Vite)
cd demo/react
npm install
npm run devThen open the printed local URL (default http://localhost:5173).
Vue 3 (Vite)
cd demo/vue
npm install
npm run devThen open the printed local URL (default http://localhost:5174).
Both demos consume this package via a local file dependency (see demo/react/package.json and demo/vue/package.json), importing ctrl-center/center.css and the framework bindings (ctrl-center/react, ctrl-center/vue).
Angular (Vite + Analog)
cd demo/angular
npm install
npm run devThen open the printed local URL (default http://localhost:5175).
Tailwind (Vite)
cd demo/tailwind
npm install
npm run devThen open the printed local URL (default http://localhost:5176).
CSS-in-JS (React + styled-components/emotion)
cd demo/css-in-js
npm install
npm run devThen open the printed local URL (default http://localhost:5177).
Next.js (SSR)
cd demo/next
npm install
npm run devThen open http://localhost:3000.
CDN (no build step)
- Open
demo/cdn.htmldirectly in your browser, or serve the repo root:
npx serve .
# then navigate to /demo/cdn.htmlBasic Usage
<!-- Import the CSS -->
<link rel="stylesheet" href="node_modules/ctrl-center/center.css">
<!-- Center a div using CSS Grid (recommended) -->
<div class="center-div">
<div>I'm perfectly centered!</div>
</div>
<!-- Or use Flexbox -->
<div class="center-flex">
<div>Also perfectly centered!</div>
</div>// ES modules
import 'ctrl-center/center.css';
// CommonJS
require('ctrl-center/center.css');📚 Centering Methods
Primary Methods
| Class | Method | Use Case | Browser Support |
|-------|--------|----------|----------------|
| center-div | CSS Grid | Modern default | IE11+ (with fallback) |
| center-flex | Flexbox | Legacy support | IE11+ |
| center-x | Horizontal only | Single axis | IE11+ |
| center-y | Vertical only | Single axis | IE11+ |
Specialized Methods
| Class | Description | Use Case |
|-------|-------------|----------|
| absolute-center | Absolute positioning | Overlays, modals |
| viewport-center | Full viewport height | Landing pages |
| fullscreen-center | Fixed fullscreen | Splash screens |
| text-center | Text alignment | Typography |
| inline-center | Inline elements | Buttons, badges |
Responsive Centering
<!-- Automatically switches between flex and grid based on container size -->
<div class="center-responsive">
<div>Smart responsive centering!</div>
</div>🎨 Customization
CSS Custom Properties
.my-container {
--center-gap: 20px; /* Space between items */
--center-padding: 30px; /* Container padding */
--center-max-width: 500px; /* Constrain child width */
--center-max-height: 300px; /* Constrain child height */
}Example with Custom Properties
<div class="center-div" style="--center-gap: 1rem; --center-padding: 2rem;">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>⚛️ Framework Integration
React
import { CenterDiv, useCenterDiv } from 'ctrl-center/react';
// Component approach
function App() {
return (
<CenterDiv gap="1rem" padding="2rem">
<div>Centered content</div>
</CenterDiv>
);
}
// Hook approach
function MyComponent() {
const centerRef = useCenterDiv({ method: 'flex', responsive: true });
return (
<div ref={centerRef}>
<div>Content</div>
</div>
);
}
// Higher-order component
const CenteredComponent = withCenterDiv(MyComponent, { method: 'grid' });Vue 3
<template>
<CenterDiv :gap="16" :responsive="true">
<div>Centered content</div>
</CenterDiv>
</template>
<script setup>
import { CenterDiv, useCenterDiv } from 'ctrl-center/vue';
// Composition API
const { centerClass, updateOptions } = useCenterDiv({
method: 'flex',
gap: '1rem'
});
</script>Angular
// Component
import { CenterDivComponent } from 'ctrl-center/angular';
@Component({
template: `
<center-div [gap]="'1rem'" [method]="'grid'">
<div>Centered content</div>
</center-div>
`
})
export class MyComponent {}
// Directive
@Component({
template: `
<div centerDiv [centerMethod]="'flex'" [centerGap]="'1rem'">
<div>Content</div>
</div>
`
})
export class MyComponent {}CSS-in-JS
import { createCenterStyles } from 'ctrl-center/css-in-js';
const styles = createCenterStyles({
method: 'grid',
gap: '1rem',
padding: '2rem',
responsive: true
});
// Usage with styled-components
const CenteredDiv = styled.div`
${styles}
`;
// Usage with emotion
const CenteredDiv = styled.div(styles);Tailwind CSS
// tailwind.config.js
module.exports = {
plugins: [
require('ctrl-center/tailwind')
]
}<!-- Use the generated utilities -->
<div class="center-grid gap-4 p-8">
<div>Centered with Tailwind!</div>
</div>♿ Accessibility Features
Built-in Accessibility
- Focus management: Proper focus outline and keyboard navigation
- High contrast: Automatic border in high contrast mode
- Reduced motion: Respects
prefers-reduced-motion - RTL support: Full right-to-left language support
- Screen readers: Semantic structure preservation
WCAG Compliance
<!-- Proper focus indicators -->
<div class="center-div" tabindex="0" role="main">
<div>Accessible centered content</div>
</div>
<!-- RTL support -->
<div class="center-flex" dir="rtl">
<div>المحتوى المتمركز</div>
</div>🔧 Guardrails & Conflict Detection
Automatic Conflict Detection
import { CenterDivGuardrails } from 'ctrl-center/guardrails';
// Start guardrails (conflict detection, a11y checks, optional perf tracking)
const guardrails = new CenterDivGuardrails({
logLevel: 'warn', // 'none' | 'warn' | 'error'
performanceTracking: true, // enable paint/layout shift tracking
a11yChecks: true, // enable accessibility checks
namespace: 'Demo' // optional console prefix
});
// Get a consolidated report at any time
console.log(guardrails.getReport());Framework Compatibility
The package automatically detects and works with:
- ✅ Bootstrap - Graceful coexistence with Bootstrap utilities
- ✅ Tailwind CSS - Complementary utility classes
- ✅ Foundation - Compatible with Foundation grid
- ✅ Bulma - Works alongside Bulma flexbox utilities
- ✅ Custom CSS - Non-destructive integration
📱 Browser Support
| Browser | Support | Notes | |---------|---------|-------| | Chrome | 88+ | Full support | | Firefox | 87+ | Full support | | Safari | 14+ | Full support | | Edge | 88+ | Full support | | IE11 | Partial | Flexbox fallback |
Progressive Enhancement
/* Modern browsers get Grid */
.center-div {
display: grid;
place-items: center;
}
/* IE11 gets Flexbox fallback */
@supports not (display: grid) {
.center-div {
display: flex;
justify-content: center;
align-items: center;
}
}⚡ Performance
Bundle Size
- Core CSS: 4.2KB minified, 1.1KB gzipped
- React components: +2.1KB
- Vue components: +1.8KB
- Angular components: +3.2KB
Performance Optimizations
- CSS containment for layout isolation
- GPU acceleration for transforms
- Layer hints for browser optimization
- Container queries for efficient responsive design
Performance Monitoring
import { CenterDivGuardrails } from 'ctrl-center/guardrails';
const guardrails = new CenterDivGuardrails({ performanceTracking: true });
// Later, read performance metrics collected so far
const { performance } = guardrails.getReport();
console.table(performance.paintTimes);
console.table(performance.layoutShifts);🧪 Testing
Running Tests
# Run all tests
npm test
# Run specific test suites
npm run test:unit
npm run test:browser
npm run test:accessibility
# Run with coverage
npm run test:coverageTest Coverage
- ✅ 43/43 tests passing (100% coverage)
- ✅ Cross-browser compatibility
- ✅ Accessibility compliance
- ✅ Performance benchmarks
- ✅ Framework integration
Writing Your Own Tests
import { assertCentered } from 'ctrl-center/test-helpers';
test('my component is centered', async ({ page }) => {
await page.setContent(`
<div class="container center-div">
<div class="content">Hello</div>
</div>
`);
await assertCentered(page, '.content', '.container');
});🔄 Migration Guide
From Custom CSS
/* Before */
.my-center {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
/* After */
.my-center {
@apply center-div; /* With Tailwind */
/* OR */
/* Remove custom CSS and use class="center-div viewport-center" */
}From Other Libraries
// From react-center
// Before
import Center from 'react-center';
<Center><div>Content</div></Center>
// After
import { CenterDiv } from 'center-div/react';
<CenterDiv><div>Content</div></CenterDiv>🛠️ Advanced Usage
Custom Centering Method
.my-custom-center {
display: grid;
grid-template-areas: ". . ." ". content ." ". . .";
grid-template-columns: 1fr auto 1fr;
grid-template-rows: 1fr auto 1fr;
}
.my-custom-center > * {
grid-area: content;
}Responsive Breakpoints
@container (max-width: 480px) {
.center-responsive {
--center-gap: 0.5rem;
--center-padding: 1rem;
}
}
@container (min-width: 1200px) {
.center-responsive {
--center-gap: 2rem;
--center-padding: 3rem;
}
}Animation Support
.animated-center {
transition: all 0.3s ease;
}
.animated-center:hover {
--center-gap: 2rem;
transform: scale(1.05);
}🐛 Troubleshooting
Common Issues
Q: My content isn't centering properly
<!-- ❌ Wrong: Missing container dimensions -->
<div class="center-div">
<div>Content</div>
</div>
<!-- ✅ Correct: Container has dimensions -->
<div class="center-div" style="height: 300px;">
<div>Content</div>
</div>Q: Multiple items aren't spacing correctly
/* ✅ Use custom properties for spacing */
.my-container {
--center-gap: 1rem;
}Q: Conflicts with my existing CSS
// Enable conflict detection and checks
import { CenterDivGuardrails } from 'ctrl-center/guardrails';
const guardrails = new CenterDivGuardrails({});Debug Mode
import 'center-div/debug.css'; // Adds visual debugging outlines🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
Development Setup
git clone https://github.com/yourusername/center-div.git
cd center-div
npm install
npm run devRunning Tests
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report📄 License
MIT License - see LICENSE for details.
🙏 Acknowledgments
- Inspired by the eternal struggle of centering divs
Remember: The hardest problem in computer science is now solved. You're welcome 🤝
