Skip to content

Instantly share code, notes, and snippets.

@bfgeek
Last active May 26, 2022 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bfgeek/60d4f57092eadcda0d4f32a8eb23b4c8 to your computer and use it in GitHub Desktop.
Save bfgeek/60d4f57092eadcda0d4f32a8eb23b4c8 to your computer and use it in GitHub Desktop.
extending-position-absolute-fixed.md

Introduction

This describes an extension to position: absolute / position: fixed which could be used to "anchor" an absolute/fixed element to another element in the DOM.

Background

Positioned absolute/fixed is a relatively powerful layout mode, as a refresher: canvas

Here absolute/fixed elements can be anywhere within the sub-tree of the containing-block (e.g. for a position: fixed element the containing-block is typically the "viewport").

They "bubble" up the DOM tree, and get positioned by the containing-block.

In the above example we have two different children:

.child1 {
  position: fixed;
  top: 30px;
  left: 20px;
}
.child2 {
  position: absolute;
  right: 20px;
  bottom: 10px;
}

Here the top/right/bottom/left "insets" are with respect to the containing-block "rect".

Extending the model

We can use the same positioning model to "anchor" to elements. For example:

canvas (1)

.anchor {
  outline: solid red;
  anchor: id; /* any valid ident */
}
.child {
  outline: solid cyan;
  position: fixed;
  top: 10px bottom id;
  right: right id; /* 0px right id */
  bottom: 10px;
}

In the above example the "insets" (top/right/bottom/left) can refer to the "sides" of an anchor. (Another way of thinking about this is that the containing-block "rect" is modified).

The only constraint here is that the element with the anchor: id needs to be within the subtree of the containing-block.

You should be able to do things like "center" this child element off anchor e.g.

canvas (2)

.child {
  position: absolute;
  top: 10px bottom anchor;
  left: left anchor;
  right: right anchor;
  width: fit-content;
  margin: auto;
}

Further extensions

This could be further extended to have multiple "fallbacks", e.g.

canvas (3)

.child {
  position: absolute;
  top: 10px bottom anchor;
  left: left anchor, auto; /* list syntax, first try slot 1, then slot 2 */
  right: auto, 10px; /* can still refer to the "default" containing block */
}

Issues

  • "Further extensions" might have issues.
  • Need way of deciding which "anchor" "wins" if multiple within containing-block subtree.
  • Insets (top/left/right/bottom) are also used for position: relative, position: sticky. Either need to make these shorthandes or use another similar property, or just say these modes "ignore" the extra information. (Solvable issue).
@Masterrag
Copy link

position: fixedgistfile1.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment