Centering using Flex

Flex makes it really easy to center elements

  • Horizontally centering inline element in block element
<div style="display: flex; justify-content: center; border: 1px solid red; width: 100%">
    <span style="border: 1px solid blue">Centered element<span>
</div>
Centered element



  • Horizontally centering multiple block level elements - use flex to center them. These will be forced into inline-block elements.
<div style="display: flex; justify-content: center; gap: 10px">
    <div style="border: 1px solid red">
        Div one
    </div>
    <div style="border: 1px solid green">
        Div two
    </div>
    <div style="border: 1px solid blue">
        Div three
    </div>
</div>
Div one
Div two
Div three



  • Vertically centering element using Flex. The parent element must have a height defined.
<div style="display: flex; justify-content: center; border: 1px solid red; width: 100%; flex-direction: column">
    <span style="border: 1px solid blue">Centered element<span>
</div>
Centered element



  • Vertically and Horizontally centering element using Flex. Again, parent element height must be specified.
<div style="display: flex; justify-content: center; border: 1px solid red; height: 100px; flex-direction: column; align-items: center">
    <span style="border: 1px solid blue">Centered element<span>
</div>
Centered element



Centering elements in CSS without flex

  • Inline element in block element using text-align
<div style="text-align: center; border: 1px solid red; width: 100%">
    <span style="border: 1px solid blue">Centered element<span>
</div>
Centered element



  • Just a block level element in another block - we will have to provide some width. The margin: 0 auto centers the div with the width specified (it must be smaller than 100%). The text-align: right centers the text within the centered div.
<div style="border: 1px solid red; width: 50%; margin: 0 auto; text-align: right">
    Right aligned text in the centerd div
</div>
Right aligned text in the centerd div




Comments

comments powered by Disqus