Go Back to Pagination

position: fixed and its main pitfall

The CSS property position: fixed is often used to create elements that stay in a fixed position on the relative to the initial containing block established by the viewport. So if you want to build a fixed topbar for example, position:fixed can be used. However, there is a relatively unknown trap when using position:fixed, that most tutorials leave out.

I'm thinking about asking a potential new hire during an interview I'm conducting next week about this, since I only learned this after a couple of years in the CSS trenches.

The pitfall

When an element with position: fixed is placed within an element that has the transform, filter or perspective property, its position will be relative to the that element rather than to the viewport.

The reason for this is that the transform property creates a new coordinate system for the transformed element (as described in the spec), which is separate from the normal flow of the document. When a fixed element is placed within a transformed element, it becomes a child of that transformed element's coordinate system, and its position is calculated relative to that system.

An example

This example illustrates a common pitfall. A couple of position:fixed leopards are kept behind a red line within a transform: translate (0,0) container element. Due to the transform property, the parent element creates a new coordinate system. position:fixed elements within it are positioned relative to it. If you toggle the checkbox, the leopards will be released because the containing element's transform property will be set to none. Once this happens, the fixed-positioned leopards will use the initial containing block and its coordinate system.

🐆🐆🐆🐆🐆🐆🐆🐆🐆

Conclusion

Feel free to play around with the code in your dev tools. I think I'll ask the new hire about this next week, since it's something a senior front-end dev should know.