2

Here's a CSS question, if we put margin: auto in normal flow, only left and right margin space being averaged. However, if we put 'margin: auto` to a flex item, the item centered on both horizontal and vertical, why is it?

Heres the code:

#one {
    width:300px;
    height:300px;
    border:solid 2px black;
    margin:auto;
    display:flex;
}

#two {
    width:100px;
    height:100px;
    background:red;
    margin:auto;
}
<div id = "one">
 <div id ="two"></div> 
</div>

Looking forward to any input!

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Arel Lin
  • 908
  • 2
  • 13
  • 24

1 Answers1

1

The functionality of the flex calculating the margin in all direction based on the parent div height and width,

i.e

  1. The div#one having the height&width of 300px

  2. The div#two having the height&width of 100px

so the margins are calculated as margin:100px;

Which means

#two{
margin-top:100px;
margin-right:100px;
margin-bottom:100px;
margin-left:100px;
}

If you need only horizontal margin then use margin:0 auto;

pradeep kumar
  • 983
  • 10
  • 21