Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center middle flexbox item and justify the rest [duplicate]

Tags:

html

css

flexbox

For an odd number of flex items I want the middle one to be in perfect center and other items just flow around it. The middle item has fixed width, all the rest are fluid and must stick to the middle item so the paddings are fixed.

enter image description here

/* CSS */

.flex-holder {
	display: flex;
	justify-content: center;
}
.middle-item {
	width: 75px;
}
<!-- HTML -->

<ul class="flex-holder">
  <li>Item 1</li>
  <li>Some item</li>
  <li class="middle-item">Middle</li>
  <li>Very long text item</li>
  <li>Test</li>
</ul>

Is it actually possible with flexbox? If no, please suggest another solution.

like image 252
Andrey Avatar asked Oct 19 '22 01:10

Andrey


1 Answers

One solution would be to use position: absolute on middle element and center it with transform: translate() but there will be overflow of elements on small window size which you can fix with media queries.

.flex-holder {
  display: flex;
  justify-content: space-around;
  position: relative;
  list-style: none;
  padding: 0;
}

.middle-item {
  width: 75px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<ul class="flex-holder">
  <li>Item 1</li>
  <li>Some item</li>
  <li class="middle-item">Middle</li>
  <li>Very long text item</li>
  <li>Test</li>
</ul>

Another solution that will get result close to desired result is to wrap li's left and right of middle li in ul's and set flex: 1 on them so they take equal size and set middle div always in center.

ul, .wrap {
  display: flex;
  justify-content: space-around;
  position: relative;
  list-style: none;
  flex: 1;
  padding: 0;
}
.middle-item {
  width: 75px;
  background: lightblue;
  text-align: center;
}
<ul class="flex-holder">
  <li class="wrap">
    <ul>
      <li>Item 1</li>
      <li>Some item</li>
    </ul>
  </li>
  <li class="middle-item">Middle</li>
  <li class="wrap">
    <ul>
      <li>Very long text item</li>
      <li>Test</li>
    </ul>
  </li>
</ul>
like image 125
Nenad Vracar Avatar answered Oct 30 '22 03:10

Nenad Vracar