Skip to content

Instantly share code, notes, and snippets.

@amekusa
Last active January 31, 2023 05:53
Show Gist options
  • Select an option

  • Save amekusa/d79530cacc874ad27b0c5278bba66c84 to your computer and use it in GitHub Desktop.

Select an option

Save amekusa/d79530cacc874ad27b0c5278bba66c84 to your computer and use it in GitHub Desktop.
oddities of `position` property
<!DOCTYPE html>
<html>
<body>
<style>
body {
background: yellow;
}
div {
min-height: 100px;
color: white;
}
.x {
position: relative;
width: 400px;
background: blue;
}
.y {
position: static;
width: 50%;
background: green;
}
.z {
position: absolute;
right: 0;
width: 50%;
background: red;
}
</style>
BODY
<div class="x">
X (relative)
<div class="y">
Y (static)
<div class="z">
Z (absolute)
</div>
</div>
</div>
</body>
</html>
@amekusa
Copy link
Author

amekusa commented Jan 30, 2023

CSS Positioning Rules

Screen Shot 2023-01-31 at 6 56 07

If position is absolute

top/right/bottom/left and width/height: <percentage> are relative to the closest ancestor of which position is not static .
Thus, in the above example, the box .z gets 50% width of the box .x, not .y. And also its aligned with the right edge of .x due to right: 0 .

If position is fixed

top/right/bottom/left and width/height: <percentage> are relative to the viewport.

If position is not absolute or fixed

width/height: <percentage> is relative to the direct parent no matter what the parent's position is.

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