How to center a checkbox in a table cell?
To center a checkbox in a table cell, use CSS flexbox. Apply display: flex;
, justify-content: center;
, and align-items: center;
to the cell. Here's the quick-hit solution:
Add the CSS to your external stylesheet and the class="checkbox-cell"
to your <td>
that contains the checkbox.
The Longest Journey is Centering the Checkbox
The Old Ways: Text-Align and Vertical-Align
Before flexbox took center stage, developers relied on text-align and vertical-align.
This will position the checkbox in the center, both vertically and horizontally.
The Wrapper Approach: Inner Div
You may want to wrap the checkbox in a div for additional control:
This gives a little extra padding to the checkbox.
Good Ol' Days: Align Attribute
The align
attribute offers a simpler method, but note that it's not recommended in strict HTML5 doctypes:
All the cool kids are using CSS now.
Fill 'em Up: Dynamic Cells
When you're messing with dynamic tables, you can use JavaScript or backend templating to drop in checkboxes:
Voila! Instant checkbox, just add JavaScript.
RWD FTW: Responsive Design
Don't forget to ensure your checkboxes play nice with different screen sizes:
This will help table and checkboxes render nicely on small screens.
Browsers Assemble! Cross-Browser Support
Cross-browser compatibility is a tough cookie. Make sure you consider support for properties like display: flex;
.
Handling More Than Checkboxes
Life isn't just about centering checkboxes. It's also about spanning rows and additional content:
Spanning Rows
If a checkbox resides in a cell spanning multiple rows, flexbox can save the day:
Styling Like a Pro
It's fine to use inline CSS for rapid demos, but for production code, opt for external stylesheets:
Compatibility Issues
Padding, borders, and explicit heights might mess with your center alignment. Make sure to check your layout across browsers and screen sizes.
Learn, Test, Collaborate
Use tools like jsFiddle for testing and collaborating.
Was this article helpful?