Home > Blockchain >  CSS - differences between horizontal and vertical flexboxes
CSS - differences between horizontal and vertical flexboxes

Time:12-12

I am using display: flex to center an item in its container. It works when I use justify-content and align-items (method 1).

In the documentation, all flexbox concepts seem to have both horizontal and vertical versions. However, using flexbox to center items doesn't seem to work when I swap the axes on everything (method 2). What is the asymmetry?

<table>
<tr>
  <th>METHOD1</th>
  <th>METHOD2</th>
</tr>
<tr>
  <td><div ><div ></div></td>
  <td><div ><div ></div></td>
</tr>
</table>

<style>

  table {
    border-spacing: 10px;
  }

  .outer {
    background-color: #ddd;
    width:  100px;
    height: 100px;
  }

  .inner {
    background-color: #f00;
    width:   20px;
    height:  20px;
  }

  .center-method-1 {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }

  .center-method-2 {
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-items: center;
  }

</style>

CodePudding user response:

There are a lot of problems in your code...

  1. div is not a self-closing tag like meta. Code like <div class=inner /> must be written as <div ></div>.

  2. Classes and IDs must always be enclosed in quotes. Something like class=inner is incorrect.

  3. justify-items will be ignored in flexbox layouts (see: https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)

  4. align-content has no effect on single line flexbox layouts (see: https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)

  5. You have a misunderstanding of how justify-content && justify-items and align-content && align-items work. For this reason you mix the properties in center-method-1 and center-method-2.

If your only goal is to center the child in the flexbox container regardless of the main-axis, then you can do it this way:

.outer {
    background-color: #ddd;
    width:  100px;
    height: 100px;
}

.inner {
    background-color: #f00;
    width:   20px;
    height:  20px;
}

.center-method-1 {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}

.center-method-2 {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
<div >
    <div ></div>
</div>

<br><br><br><br>

<div >
    <div ></div>
</div>

  • Related