How to vertically center a `` inside a div?
To vertically center a <span>
inside a div
, simply set the containing div
to display: flex;
and align-items: center;
:
Flexbox methodology empowers developers to achieve precise vertical alignment without the cascading padded jacket monster or absolute positioning witchcraft. π§ββοΈ
Direct approach - Line-height
For those just looking to center single lines of text, consider setting the line-height
of <span>
to match the height
of the div
:
Voila! Lines of text now align smack-bang in the center, thanks to our good old friend line-height
β pandering to our ascenders and descenders alike!
The wizard's touch - Positioning and Transforms
Feeling adventurous? Perhaps your <span>
is more of a changeling? Fear not! Use a combination of relative and absolute positioning with CSS transform
magicβ¨:
Off-stage and into the center spotlight, our fearless <span> comes regardless of its size. Give it up for the CSS transform
! π
Cater to the crowd - Multiple spans
Multiple performers? Give them all a standing ovation with perfect centering:
Mind the gap - Padding and borders
Skeptic about padding
and borders
? We have you covered:
With box-sizing: border-box;
, padding infestations have left the chat. π
Centering alternatives
display: inline-block
withvertical-align:middle
: Usevertical-align: middle;
alongside a pseudo-element for inline joy.
display:table-cell
method: Grid layouts lovedisplay: table;
anddisplay: table-cell;
combined withvertical-align: middle;
.
- Mobile responsiveness:
Never ignore the thumbs. In the tiny universe of mobile screens β
flexbox
ortransform
remain your best allies:
Was this article helpful?