How can I vertically center a div element for all browsers using CSS?
A bulletproof way to vertically center a <div>
in all browsers—especially older ones—is to use the table-cell technique. You make the parent act like a table and the child a table cell with vertical-align: middle;
.
.parent { display: table; /* Table-like container */ width: 100%; /* or any fixed/auto width */ height: 100vh; /* or a fixed height, e.g. 500px */ margin: 0; /* remove default body margins if needed */ } .child { display: table-cell; vertical-align: middle; text-align: center; /* optional if you also want horizontal centering */ }
In this setup, .child
is vertically centered inside .parent
without relying on modern methods (like Flexbox) that might have limited support in older browsers.
Other Common Approaches
-
Flexbox (Modern Browsers)
.parent { display: flex; align-items: center; /* vertical centering */ justify-content: center; /* optional horizontal centering */ height: 100vh; /* or another fixed height */ }
- Pros: Concise, powerful, widely supported in modern browsers.
- Cons: Older browsers (IE9 and below) lack full Flexbox support.
-
Absolute Positioning + Transform
.parent { position: relative; height: 100vh; /* or fixed height */ } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
- Pros: Works in many older browsers.
- Cons: Requires a known container height (100vh, fixed px), can be tricky with responsive designs.
-
Line-Height Trick (For Single-Line Text)
.parent { line-height: 200px; /* match container height */ height: 200px; /* fixed height */ text-align: center; /* optional horizontal centering */ } .child { display: inline-block; /* to respect line-height alignment */ vertical-align: middle; }
- Pros: Very simple for single-line text.
- Cons: Breaks if the content wraps to multiple lines or the container is fluid.
Key Takeaway
For maximum backward compatibility (including older Internet Explorer versions), use the table-cell technique. If you’re targeting modern browsers, Flexbox is usually the easiest and most flexible way to vertically center elements.
CONTRIBUTOR
TechGrind