I have a flexbox (see code snippet below as an example).
I want to set it up so that in all cases, is in the center of the flex-box and the other spans will flow around it, Based on their markup.
I'm basically looking for the align-self
CSS code, but for the main axis, not the horizontal axis (which might help explain what I'm asking for).
I also applied margin: auto;
to my which I learned after reading this article (a Great page, but it still leaves me with my following questions - except that I don't fully understand everything).
This is the code I get:
.container { align-items: center; border: 1px solid red; display: flex; justify-content: center; width: 100%; } h2 { margin: auto; ]
I'm an h2
I'm span 1 I'm span 2 I'm span 3 I'm span 1 I'm span 2 I'm span 3 I'm an h2
I'm span 4 I'm span 5 I'm span 6 I'm span 1 I'm span 2 I'm an h2
I'm span 3
To restate my question completely: I want to know how to center
on my page so that no matter what other
where code>,
will always be at the dead center of the flexbox.
P.S.: I'm willing to use JavaScript and jQuery, but I prefer a pure CSS way of doing this.
After Michael Benjamin answered:
His answer made me think. While I haven't found a way to do this yet, I believe the following is a step in the right direction:
HTML
I'm span 1 I'm span 2 I'm span 3I'm an h2
I'm span 4 I'm span 5 I'm span 6
CSS
.container div { flex: 1 1 auto; text-align: center; } h2 { flex: 0 0 auto; margin: auto; }
.container { align-items: center; border: 1px solid red; display: flex; justify-content: center; width: 100%; } .container div { flex: 1 1 auto; text-align: center; } h2 { flex: 0 0 auto; margin: auto; }
I'm an h2
I'm span 1 I'm span 2 I'm span 3 I'm span 1 I'm span 2 I'm span 3 I'm an h2
I'm span 4 I'm span 5 I'm span 6 I'm span 1 I'm span 2 I'm an h2
I'm span 3
Basically, the theory is that while the total number of As you can see in the code snippet above, I have tried ( is unknown, there are known to be three elements in total:
< div>
flex: 0 0 auto
and flex: 1 1 auto
etc.) to let It works but hasn't worked yet. Can anyone tell me if this is a step in the right direction and how to push this into an actual product?
One way is to add empty spans on both sides and then set the span and h2 to some elastic value like this:
So you ensure that the space on both sides is equal. The only problem then is that you have to decide how wide you want h2 to take.
Flex alignment properties work by allocating available space in the container.
Therefore, when a Flex item shares space with other items, there is no single-step method to center it,unless the total length of the sibling items on both sides is equal.
In the second example,
h2
the total span length on both sides is equal. Therefore,h2
is completely in the center of the container.