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?
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
When you enable the flex display setting for a parent element, the children align left and stack horizontally by default. Flex containers will not affect or change the layout of the children within their direct, child elements.
Centering with Flex Properties The easiest way is to use the flex properties and add it to the parent container using the align-items and justify-content .
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.
This is the answer
.flex {
display: flex;
justify-content: space-between;
& > *:only-child {
margin: auto;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With