2 个相对定位的 div?

发布于 2024-10-29 13:26:23 字数 261 浏览 5 评论 0原文

我有一个具有相对定位的容器 div,然后里面的另一个 div 也具有相对定位:

<div class="first">
  <div class="second">
    <img src="img.jpg" />
  </div>
</div>

我希望具有绝对定位的图像相对于“第二个”div 而不是“第一个”。但我需要它们都具有相对定位,如何指定图像相对于“第二个”div?

I have a container div that has relative positioning, then another div inside that also has relative positioning:

<div class="first">
  <div class="second">
    <img src="img.jpg" />
  </div>
</div>

I would like an image with absolute positioning to be relative to the "second" div not the "first". But I need them both to have relative positioning, how do I specify so the image is relative to the "second" div?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吝吻 2024-11-05 13:26:23

在页面层次结构中,图像将相对于 .second;但是,您必须将父母定义为相对适合孩子照顾的位置

请参阅:http://css-tricks.com/absolute-positioning-inside-相对定位/

.second { position:relative; }
.second img { position:absolute; top:0; left: 0 }

In the page hierarchy the image would be relative to .second; however, you must define the parent to be relatively positioned for the child to care.

see: http://css-tricks.com/absolute-positioning-inside-relative-positioning/

.second { position:relative; }
.second img { position:absolute; top:0; left: 0 }
不知所踪 2024-11-05 13:26:23

根据 CSS 标准,它自动相对于第二个

,因为它嵌套在第二个

中并且该 div 已定位。以下是CSS2 标准的引用:

定位框的包含块由最近的定位祖先建立

,因此您在 DOM 树中向上计数,即从最近的祖先到文档根,并在第一个定位的祖先处停止(如果没有,则它是最近的容器,但这不适用于此处)。在本例中,这将是您想要的 div.second

It is relative to the second <div> automatically according to the CSS standards, since it is nested in the second <div> and that div is positioned. Here is a quote from the CSS2 standard:

The containing block for a positioned box is established by the nearest positioned ancestor

So you count upwards in the DOM tree, i.e. from the nearest ancestor towards the document root, and stop at the first positioned ancestor (and if there isn't one, then it's the closest container, but that doesn't apply here). In this case, that will be div.second like you want.

夜无邪 2024-11-05 13:26:23
.second img{ position:absolute; top:0; left:0; }

定位仅是示例;您可以更改它以满足您的需要。

.second img{ position:absolute; top:0; left:0; }

The positioning is just an example; you can change it to suit your needs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文