What is the difference between centering with "align-items: center" or "margin"?

Asked

Viewed 164 times

-2

I saw that it is possible to centralize a div or img with display:flex, align-items: center or with the margin.

What is the difference between these two to centralize?

2 answers

2

The difference is that the margin:auto aligns both vertically and horizontally at the same time, meaning it will center the element inside the axis X and Y simultaneously.

Already justify-content: center; will align centering only horizontally (axis X)

And align-items: center; will align centering only vertically (axis Y)

**

See the image code above

body {  display: flex;}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  display: flex;
  margin-right: 10px;
}

.filho {
  width: 50px;
  height: 50px;
  background-color: red;
}

.jc {
  justify-content: center;
}

.ac {
  align-items: center;
}

.ma{
  margin: auto;
}


  
<div class="box jc">
  <div class="filho">justify-content: center;</div>
</div>

<div class="box ac">
  <div class="filho">align-items: center;</div>
</div>

<div class="box">
  <div class="filho ma">margin: auto;</div>
</div>

In addition, with margin you can have self only on the axle X or on the axle Y, guy margin: 0 auto; This code will put margin 0 on the axis Y and auto on the axis X.

Already with justify-content: center; or align-items: center; vc will not be able to individually control each side (right or left), with these two opposites the child element will always be aligned proportionally in the exact center. Already with margin you could use margin-left: auto; or margin-top: auto; etc....

Face the best way to learn is by testing takes this code ai of example and plays with it changing the values of the properties and seeing how it works.

2

Shallow: The align-items: center ensures that flex-items within a flex display element center (vertically and horizontally).

By margin you can do the same thing but it can be more complicated by depending on the size of the box (parent and child), display and position. mainly when it comes to vertical alignment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.