Search code examples
htmlcsscss-grid

Justify-self not working on absolutely positioned elements in Chrome


justify-self doesn't appear to be having any effect for elements with position: absolute or position: fixed set in Chrome.

MDN says

For absolutely-positioned elements, it aligns an item inside its containing block on the inline axis, accounting for the offset values of top, left, bottom, and right.

so I expected Chrome to follow EdgeHTML-based Edge and Firefox in aligning the elements, but it doesn't appear to have any effect. I don't have an Apple machine to test on so I'm not sure how Safari would render the page.

Setting right: 0 correctly moves the element to the right edge of the page, but that workaround doesn't work if your page relies on having elements aligned along a grid axis.

The same behaviour also occurs with align-self, again contradicting what MDN says:

Its behavior depends on the layout model, as described for justify-self.

body {
  display: grid;
  width: 100vw;
  height: 100vh;
  margin: 0;
}

#absolute {
  position: absolute;
  align-self: end;
  justify-self: end;
}
<div id="absolute">
  <p>This element is absolutely positioned at the container's end.</p>
</div>


Solution

  • Just add position: relative to the grid container.

    body {
      display: grid;
      height: 100vh;
      margin: 0;
      position: relative; /* new */
    }
    
    #absolute {
      position: absolute;
      align-self: end;
      justify-self: end;
    }
    <div id="absolute">
      <p>This element is absolutely positioned at the container's end.</p>
    </div>

    As part of the work done by Igalia in the CSS Grid Layout implementation on Chromium/Blink and Safari/WebKit, we’ve been implementing the support for positioned items. Yeah, absolute positioning inside a grid.

    Actually there’s not such a big difference compared to regular grid items. When the grid container is the containing block of the positioned items (e.g. using position: relative on the grid container) they’re placed almost the same than regular grid items.

    https://blogs.igalia.com/mrego/2016/05/27/css-grid-layout-and-positioned-items/