【问题标题】:Absolute Positioning is not working as I wanted to绝对定位没有按我的意愿工作
【发布时间】:2021-08-16 23:39:21
【问题描述】:

我尝试定位的元素仍然位于其父元素内部,即使我已将其定位为绝对位置。

HTML

<div class="panel">
  '... other elements'
  <cuik-url-box
    (urlsEvent)="setUrls($event)"
    [hidden]="!state.urlToggle"
  ></cuik-url-box>
  <cuik-img-upload
    (files)="setTempImages($event)"
    [hidden]="!state.imgUploadToggle"
  ></cuik-img-upload>
</div>

SCSS

.panel {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 500px;
  height: 80vh;
  overflow-y: auto;
  background-color: theme.$secondary;
  border: 2px solid theme.$primary;
  border-radius: 20px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: theme.$primary;
  font-family: theme.$Poppins;

  cuik-url-box,
  cuik-img-upload {
    position: absolute;

    &:is(cuik-url-box) {
      top: 50%;
      right: -50%;
      transform: translate(0%, -50%);
    }
    &:is(cuik-img-upload) {
      top: 50%;
      left: -50%;
      transform: translate(0%, -50%);
    }
  }
}

继承人的风格

cuik-app-creator,
cuik-app-editor {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba($color: theme.$secondary, $alpha: 0.05);
}

这是它的样子: enter image description here

【问题讨论】:

    标签: html css angular sass positioning


    【解决方案1】:

    An absolutely-positioned element is positioned relative to its closest positioned ancestor。也就是说,对于应用了一些非static position 样式的最近祖先。这在没有定位的祖先时是&lt;body /&gt;元素。

    例如,这里是一个包含祖先的情况没有定位,所以absolute元素是相对于视口的:

    .parent {
      height: 100px;
      width: 100px;
      border: black solid 2px;
    }
    
    .child-element {
      border: black dashed 2px;
      position: absolute;
      right: 0;
      bottom: 0;
    }
    <div class="parent">
      <p>Parent Element<p>
      <div class="child-element">
        <p>Child Element</p>
      </div>
    </div>

    现在看看如果我们将position: relative 添加到父元素会发生什么:

    .parent {
      height: 100px;
      width: 100px;
      border: black solid 2px;
      position: relative; /* In this example the parent is relatively-positioned */
    }
    
    .child-element {
      border: black dashed 2px;
      position: absolute;
      right: 0;
      bottom: 0;
    }
    <div class="parent">
      <p>Parent Element<p>
      <div class="child-element">
        <p>Child Element</p>
      </div>
    </div>

    如您所见,在第一个 sn-p 中,子项相对于视口定位,而在第二个中,子项相对于包含父项进行定位。

    如果您希望绝对定位的元素相对于视口定位,则需要从所有祖先中删除定位,或者需要将其附加到 &lt;body /&gt; 的末尾(或以其他方式移动它在层次结构中向上直到它不包含在定位元素中,但将其隐藏在任意位置可能会导致可维护性差)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-26
      • 2021-12-02
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      相关资源
      最近更新 更多