attachToContainingBlock method

void attachToContainingBlock(
  1. RenderBox? containingBlockRenderBox, {
  2. RenderBox? parent,
  3. RenderBox? after,
})

Implementation

void attachToContainingBlock(
    RenderBox? containingBlockRenderBox,
    { RenderBox? parent, RenderBox? after }
    ) {
  if (parent == null || containingBlockRenderBox == null) return;

  RenderBoxModel renderBoxModel = this;
  CSSPositionType positionType = renderBoxModel.renderStyle.position;
  // The containing block of an element is defined as follows:
  if (positionType == CSSPositionType.relative
      || positionType == CSSPositionType.static
      || positionType == CSSPositionType.sticky
  ) {
    // If the element's position is 'relative' or 'static',
    // the containing block is formed by the content edge of the nearest block container ancestor box.
    attachRenderBox(containingBlockRenderBox, renderBoxModel, after: after);

    if (positionType == CSSPositionType.sticky) {
      // Placeholder of sticky renderBox need to inherit offset from original renderBox,
      // so it needs to layout before original renderBox.
      _attachPositionPlaceholder(containingBlockRenderBox, renderBoxModel, after: after);
    }
  } else {
    // Set custom positioned parentData.
    RenderLayoutParentData parentData = RenderLayoutParentData();
    renderBoxModel.parentData = CSSPositionedLayout.getPositionParentData(renderBoxModel, parentData);
    // Add child to containing block parent.
    attachRenderBox(containingBlockRenderBox, renderBoxModel, isLast: true);

    // If container block is same as origin parent, the placeholder must after the origin renderBox
    // because placeholder depends the constraints in layout stage.
    RenderBox? previousSibling = containingBlockRenderBox == parent ?
    renderBoxModel : after;

    // Add position holder to origin position parent.
    _attachPositionPlaceholder(parent, renderBoxModel, after: previousSibling);
  }
}