Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center when only a single item in flexbox [duplicate]

Tags:

html

css

flexbox

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?

like image 886
port5432 Avatar asked Dec 24 '17 17:12

port5432


People also ask

How do I center a single element in flexbox?

To center the inner div element we will make the parent a flex container. By adding the display: flex; property we make the section element a flex container allowing us to adjust the layout of the div which is now a flex item. To center out item horizontally we use the justify-content: center; .

How do I align one flex item right?

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

Does flexbox work with position fixed?

position:fixed makes flexbox not workable, since it overrides the position of <p>Hello</p> Try to remove it and see the difference. If you want align-items:center works; try to set height: 100vh; since the body height of webview is not set to screen height by default.


2 Answers

.footer > :only-child
{
    margin-left: auto;
    margin-right: auto;
}
like image 94
CyberAP Avatar answered Sep 21 '22 08:09

CyberAP


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>
like image 37
laurent Avatar answered Sep 23 '22 08:09

laurent