3

I got a responsive design, which has 3 items in a row. If the screen gets smaller, the first one will be deleted. So the 3 items are distributed with flexbox and justify-content:space-between, which makes the outer items bound to the sides and the middle item centered. Now if the first item is deleted, I want to be the right item on the right side and the left item centered to the space which is left.

This is my code for the 3 items:

<div style="display:flex;flex-flow:row;justify-content:space-between;align-items:center">
   <span style="width:70px;text-align:right">To the left</span> 
   <div style="height:40px;width:100px;background-color:red">Center</div>
   <span style="width:70px;text-align:right">To the right</span>    
</div>

And this for the two items:

<div style="display:flex;flex-flow:row;justify-content:space-between;align-items:center">
   <div style="height:40px;width:100px;background-color:red">Center</div>
   <span style="width:70px;text-align:right">To the right</span>    
</div>

I got some fiddle for you: https://jsfiddle.net/msLd7g5j/1/

Edit: Note this is not a duplicate, at least not to the one you pointed out, because I want the left item centered to the space which is 'left over' and not centered absolutely.

Solution: I got a new fiddle: https://jsfiddle.net/msLd7g5j/2/

I just don't delete the third element, instead I delete the content, so the Element looks like

<span> </span>

the flexbox just does it job and centers the middle element to the relative middle, with justify-content:space-between set.

bflemi3
  • 6,698
  • 20
  • 88
  • 155
TobiasW
  • 861
  • 3
  • 13
  • 36

1 Answers1

1

So you want:

...the right item on the right side and the left item centered to the space which is left.

...the left item centered to the space which is 'left over' and not centered absolutely.

Your solution (posted at the bottom of your answer) looks pretty good. You remove all content from the first flex item and give it a zero width. With justify-content: space-between, this centers the second flex item between the left edge of the container and the left edge of the next element. This appears to work perfectly.

An alternative method would be to remove the first flex item (display: none). Wrap the content of the middle flex item in a span. Move all inline styles from the parent to the child. Then apply width: 100%; text-align: center; to the parent.

<div style="display:flex; flex-flow:row; justify-content:space-between;align-items:center">
    <span style="text-align:right; display: none;"> </span> 
    <div style="width: 100%; text-align: center;"><span style="display: inline-block;
                    width:100px; background-color:blue; height: 40px;">Center</span></div>
    <span style="width:70px;text-align:right">To the right</span>   
 </div>

DEMO: https://jsfiddle.net/msLd7g5j/4/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701