列表元素内的绝对定位

5

我正在尝试基于视口定位一些列表元素,但它们最终会粘在其父级上。

为了重现这个问题,我只需要创建一个带有绝对定位的列表元素:

body {
  background-color: lightgray;
}

ul {
  position: absolute;
  top: 50px;
  left: 50px;
  list-style: none;
}

.element {
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
}
<ul>
  <li>
    <div class="element">
      <p>
        Element
      </p>
    </div>
  </li>
</ul>

正如您所看到的,该元素并非定位在视口的左上角,而是相对于 ul 定位。

我是否遗漏了什么?可能是 li 元素的静态位置导致的吗?


2
"absolute" 相对于 "positioned" 元素而言...在 li 中添加 position: relative... - kukkuz
它只会使元素相对于li的位置变得相对,而不是相对于视口。 - Thomas Ferro
尝试一下并观察以下代码的行为:.element { position: absolute; top: -40; left:200; background-color: red; } - Liaqat Saeed
除非我在末尾添加“px”,否则顶部和左侧样式不会自动应用,而且位置仍然不正确。 - Thomas Ferro
3个回答

2
尝试使用position: fixedposition: absolute会将元素绝对定位于最近的定位祖先元素(在此情况下为具有position: absoluteul),而position: fixed将元素相对于视口*定位。

代码片段:

body {
  background-color: lightgray;
}

ul {
  position: absolute;
  top: 50px;
  left: 50px;
  list-style: none;
}

.element {
  position: fixed;
  top: 0;
  left: 0;
  background-color: red;
}
<ul>
  <li>
    <div class="element">
      <p>
        Element
      </p>
    </div>
  </li>
</ul>

* 但是有一些例外情况,例如祖先元素上的 transform 将会破坏这种行为。


1
如果您希望将元素的位置相对于视口进行设置,则父级(ul)不应该具有position:absolute,因此:
方法1) 移除ulposition: absolute:

body {
  background-color: lightgray;
}

ul {
  top: 50px;
  left: 50px;
  list-style: none;
}

.element {
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
}
<ul>
  <li>
    <div class="element">
      <p>
        Element
      </p>
    </div>
  </li>
</ul>

方法2)更改HTML代码:

body {
  background-color: lightgray;
}

ul {
  position: absolute;
  top: 50px;
  left: 50px;
  list-style: none;
}

.element {
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
}
<ul>
  <li>
    <!--Other Content -->
  </li>
</ul>
<div class="element">
      <p>
        Element
      </p>
</div>


由于所给的解决方案有效,我会为你的回答点赞。不幸的是,由于其他限制,我无法从 ul 中删除 position: absolute 或更改 HTML。FYI:@Jesse de Bruijne 的解决方案是我正在寻找的,使用固定位置而不是绝对位置。 - Thomas Ferro
@ThomasFerro,感谢您的点赞。但是如果您为元素设置了position:fixed,它将固定在原位,不会随页面滚动而移动。可以尝试使用body { height: 2200px;}并滚动页面查看结果。 - Ehsan
在这种特定情况下,这种行为非常适合我,因为我的应用程序的宽度和高度设置为100%,每个组件都管理自己的溢出。 - Thomas Ferro

0
请试试这个。在 ul 类中删除 position:absolute 并设置为 position:relative。同时,bodyul 元素都有默认的 margin 值,需要将它们移除。

body {
  background-color: lightgray;
  margin:0;
}

ul {
  position: relative;
  list-style: none;
  margin:0;
}

.element {
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
}
<ul>
  <li>
    <div class="element">
      <p>
        Element
      </p>
    </div>
  </li>
</ul>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接