Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a flex item when it is an only child

Tags:

css

flexbox

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?

like image 907
haki Avatar asked Aug 17 '17 08:08

haki


People also ask

How do you center photos in Flex?

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.

Does display flex affect all children?

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.

How do I center an item in Flex?

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 .


2 Answers

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 margins

Prior to alignment via justify-content and align-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.

like image 58
Michael Benjamin Avatar answered Sep 30 '22 19:09

Michael Benjamin


This is the answer

.flex {
    display: flex;
    justify-content: space-between;

    & > *:only-child {
        margin: auto;
    }
}
like image 43
haki Avatar answered Sep 30 '22 21:09

haki