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...
div
is 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=inner
is incorrect.justify-items
will be ignored in flexbox layouts (see: https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)align-content
has 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-items
andalign-content
&&align-items
work. For this reason you mix the properties incenter-method-1
andcenter-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>