How can I center text (horizontally and vertically) inside a div block?
To center text inside a div block, apply display: flex;, justify-content: center;, and align-items: center; to the div. Here's the CSS snippet:
And pair it with this HTML tag:
This simple configuration will center your text both horizontally and vertically.
Using flexbox: a modern approach
By neatly aligning your elements on both axes, Flexbox turns the task of centering into a walk in the park.
Be aware not all flex content are created equal. To center your content nicely within a shrink-wrapped flex-item, ditch the flex: ... and let margin: auto take control.
For the old but gold Internet Explorer, the transform trick with position: relative doesn't skip a beat.
Time-tested tricks: classic methods
If you want to give the classic methods a shot or cross-browser compatibility is your top priority, go for position: relative; mixed with transform.
Vertical alignment for multi-line text or tweaking line-height for single-line text works well, but ensure the parent div height is well-defined. Don't forget to align your inline and block elements using text-align: center; and margin: 0 auto; respectively.
Vertical and horizontal: achieving balance
Flexbox has another ace up its sleeve, the flex-direction: column; allows for beautiful stacking alongside vertical centering. For non-flexbox approach, display table-cell with vertical-align: middle; holds strong even today.
Specific situations and their handling
Unique alignment problems require unique solutions. Let's solve a few:
Dynamic Responsive Design
In the world of different screen sizes, viewport units will scale elegantly with the window:
Dynamic Heights
In case your div’s height is dynamic, the transform method works like a charm:
Inline-Block Display
Inline elements can be painlessly centered by tweaking text-align:center; on the parent and vertical-align:middle; with display:inline-block; for the children:
Single Line Scenario
For single line text, setting the line-height to match your div’s height works like a charm. With overflow: hidden; you’re covered against unexpected spillage.
Tips for precision
- Ensure to define parent dimensions when using percentages.
- visual alignment can be achieved by adding a border (
1px solid silver;). - Distinct background color can clearly highlight positioned elements.
- Check the parent element styles; a height of 100% can disrupt if
htmlorbodytag doesn’t have it set.
Was this article helpful?