position的relative和absolute分別是相對誰進行定位的?

王铁柱6發表於2024-12-09

In front-end development, position: relative; and position: absolute; work relative to different elements:

  • position: relative;: An element with position: relative; is positioned relative to its normal position in the document flow. Think of it as offsetting the element from where it would have been without any positioning applied. Other elements in the flow are not affected; they still flow around the element's original position. The offsets are controlled by top, bottom, left, and right.

  • position: absolute;: An element with position: absolute; is positioned relative to its nearest positioned ancestor. This means it looks up the DOM tree for the closest parent element that has a positioning context other than static (the default). Common positioning contexts are relative, absolute, fixed, and sticky. If no positioned ancestor is found, it's positioned relative to the initial containing block (usually the <html> element, effectively the viewport). The element is removed from the normal document flow, meaning other elements will behave as if it wasn't there. Again, top, bottom, left, and right control the offsets.

Here's a simple analogy:

Imagine a family photo.

  • relative: You move slightly in the photo, but everyone else stays in their original spots. There's a bit of a gap where you "used to be."

  • absolute: You're cut out of the photo and placed somewhere else entirely, perhaps stuck to the frame or another person. The rest of the family doesn't rearrange themselves to fill the space where you were.

Key differences summarized:

Feature position: relative; position: absolute;
Reference Normal position Nearest positioned ancestor or initial containing block
Document Flow Remains in flow Removed from flow
Effect on other elements None Other elements fill the original space

Understanding these differences is crucial for creating complex layouts and controlling the positioning of elements on a web page.

相關文章