Reputation: 9759
I have a flex container that can contain one or more elements.
If there is more than one element I want to justify content using space-between
justify-content: space-between;
If there is only one element I want it to be centered.
Example codepen
Is this possible using only CSS?
Upvotes: 11
Views: 4387
Reputation: 371231
Yes. The flexbox specification makes this possible.
.flex {
display: flex;
margin: 1em 0;
padding: 1em;
border: 1px solid red;
justify-content: space-between;
}
a:only-child {
margin: 0 auto;
}
<div class="flex">
<a>item 1</a>
<a>item 2</a>
</div>
<div class="flex">
<a>item 1</a>
</div>
From the spec:
8.1. Aligning with
auto
marginsPrior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
So, basically, use justify-content
on the parent and an auto margin on the child.
Per the rule above, the auto margin takes precedence when the only-child
selector applies.
Upvotes: 11
Reputation: 9759
This is the answer
.flex {
display: flex;
justify-content: space-between;
& > *:only-child {
margin: auto;
}
}
Upvotes: 5
Reputation: 8726
Just add margin: auto
to your item. Hope it is what you are looking for.
.flex {
display: flex;
margin: 1em 0;
padding: 1em;
border: 1px solid red;
justify-content: space-between;
}
a {
margin: auto;
}
<div class="flex">
<a>item 1</a>
<a>item 2</a>
</div>
<div class="flex">
<a>item 1</a>
</div>
Upvotes: 1