Absolute positioned item in a flex container still gets considered as item in IE & Firefox
Asked Answered
P

3

8

If I have multiple elements with the property justify-content: space-between in a flex container and I want to absolute position one of them and remove from the flex flow, as showed here: hoped result

This works in Chrome but not in IE and Firefox as the absolute positioned element is considered as 0 width, but still in the flex flow: bugged result

Is there a fix to this keeping the layout as it is?

CodePen

Pulse answered 28/4, 2015 at 22:17 Comment(0)
T
4

It turns out that all it takes is three simple steps

(Demo)

1). Set the left and right margin to auto on each child

img {
    margin-left: auto;
    margin-right: auto;
}

2). Set the left margin on the first child to 0

img:nth-child(2) {
    margin-left: 0;
}

3). Set the right margin on the last child to 0

img:last-child {
    margin-right: 0;
}

If you miss any of these steps it will not work properly

This works in firefox and chrome, I haven't tested it in any other browsers.

EDIT:

Thanks to @Pontiacks

Apparently you can get away with adding margin-left: auto to the img:nth-child(2)

updated jsfiddle

Tiro answered 28/4, 2015 at 23:36 Comment(0)
S
2

I have a much simpler hack to solve this particular problem.

div {
  background-color: #66BB66;
  display: flex;
  position: fixed;
  width: 100%;
  justify-content: space-between;
}
div > img:nth-child(2) {
  position: absolute;
  left: 0;
}
<div>
  <img src="http://www.fillmurray.com/150/150">
  <img src="http://www.fillmurray.com/150/100">
  <img src="http://www.fillmurray.com/150/150">
</div>

Just change the order in the DOM. The absolutely positioned element is still positioned wherever you put it, and although flexbox still treats it like it is in the flow, its position in the flow (in the dom) causes flexbox to allocate space the same way across browsers.

I believe you could use the order property to achieve the same thing.

Sardanapalus answered 9/8, 2016 at 17:23 Comment(1)
This one worked in my case, the other solution didn't.Stylography
B
0

I found that none of these handled my case, as I have three elements I want to have evenly spaced, and one absolutely positioned sibling. I found the trick in this case is just to add margin-right: auto to the first element to be evenly spaced, and margin-left: auto to the last element to be evenly spaced. You can check it out at this fiddle http://jsfiddle.net/tch6y99d/

Beefsteak answered 11/1, 2017 at 22:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.