
How to center element : CSS
If you are reading this, then you already know how difficult it is to center things in CSS especially “Vertical”.
In this post, i will share some of ways to center element, text with the help of pure CSS. First lets look at easy ways to center text then we will move on to centering element which is quite difficult.
I am using inline style for demonstration purpose only please use css classes.
Text Centering
You can use text-align:center; to align text into center within Block level element.
<div style='text-align:center'>CSS Centering</div>
You can use height & line-height to align text vertically.You have to set height & line-height to same pixel’s or other CSS pixel unit.
<div style='height:50px;line-height:50px;'>CSS Centering</div>
Content Centering
Well, Its quite difficult to center content(i.e. elements) & there are multiple ways to center content
Using text-align
Use text-align:center to horizontally align inline-element(eg span tag) within block level element(eg. div).
<div style='text-align:center'><span>CSS Centering</span></div>
Using margin
set content width & height to some unit, & set its parent margin to “auto”.use 0 auto to align vertical, use auto 0 to align horizontal and use auto to align center & horizontally.
<div style="margin:auto;">
<div style="width:200px;height:auto;">CSS Centring</div>
</div>
Using Transform & Position
Set parent position as relative or absolute, then set child content position as absolute & its top to 50% and transform:translateY(-50%) to align vertically center. use left 50% and transform:translateX(-50%) to align horizontally.use both(left,top) and translateX,translateX to center vertically & horizontally.
<div style="position:relative;">
<div style="position:absolute:top:50%;left:50%;transform:translateX(-50%) transform:translateY(-50%)">CSS Centring</div>
</div>
Using Flex Box
Set parent display mode to flex & justify-content property to center.Its that easy with flex box.You don’t have to worry about set any position. Only downside with this method is that not all browser support this display method but most of them do,so you can use this method if you are only targeting newer browser.
<div style="display:flex;justify-content:center;">
CSS Centering
</div>
Thanks for reading…