8

I have a flexbox-controlled footer. It can contain 1,2 or 3 subordinate divs.

.footer {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

<div class='footer'>
  <div>Left</div>
  <div>Middle</div>
  <div>Right</div>
</div>

With 2 or 3 divs, the css above works fine:

  • with three, Left and Right are flushed left and right and Middle is in the middle.
  • with 2 they are flushed left and right

But with a single div, it is left-justified. I would prefer it would be centered.

How can I adjust the css so that in the case of a single div it will be centered, while retaining the behaviour for 2 or 3 divs?

Asons
  • 84,923
  • 12
  • 110
  • 165
port5432
  • 5,889
  • 10
  • 60
  • 97
  • 1
    For anybody not needing `space-between`, `space-around` centers a single item by design [(jsfiddle demo](https://jsfiddle.net/fx6pw1hd/)). Here's the explanation: https://stackoverflow.com/q/36487476/3597276 – Michael Benjamin Dec 24 '17 at 17:31

3 Answers3

14
.footer > :only-child
{
    margin-left: auto;
    margin-right: auto;
}
CyberAP
  • 1,195
  • 1
  • 11
  • 17
5

you can make sure your items grow with the available space so their content will be located relatively to the item

.footer > div {
   flex-grow:1:
   text-align: center; // for example
}

.footer {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.footer > div {
 flex-grow:1;
 text-align:center; //for example
}
<div class='footer'>
  <div>Left</div>
  <div>Middle</div>
  <div>Right</div>
</div>
laurent
  • 2,590
  • 18
  • 26
3

If you want to use the margin to just do that, adjust margin, you can use space-evenly, or the cross browsers trick with pseudo elements and your existing space-between

Stack snippet - pseudo + space-between

.footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.footer::before, .footer::after {
  content: '';
}
<div class='footer'>
  <div>Left</div>
  <div>Middle</div>
  <div>Right</div>
</div>

Stack snippet - space-evenly (browser support)

.footer {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}
<div class='footer'>
  <div>Left</div>
  <div>Middle</div>
  <div>Right</div>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165