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...
divis not a self-closing tag likemeta. Code like<div class=inner />must be written as<div ></div>.Classes and IDs must always be enclosed in quotes. Something like
class=inneris incorrect.justify-itemswill be ignored in flexbox layouts (see: https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)align-contenthas no effect on single line flexbox layouts (see: https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)You have a misunderstanding of how
justify-content&&justify-itemsandalign-content&&align-itemswork. For this reason you mix the properties incenter-method-1andcenter-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>
