使用CSS相对于不是其父级的另一个div定位一个div

编程入门 行业动态 更新时间:2024-10-28 14:21:46
本文介绍了使用CSS相对于不是其父级的另一个div定位一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道使用 position:relative 和 position:absolute 技巧将div相对于其父级进行定位.但是,如果div不是它的父级,而我想相对于它定位呢?我正在尝试按照这些思路实施一些事情.

I'm aware of the position:relative and position:absolute trick to position a div relative to its parent. But what if the div is not its parent and I want to position it relative to that? I'm trying to implement something along those lines.

我也知道 position:fixed 可以修复div,但是我正在构建一个响应式网站,因此我想避免这种情况.我在这里发现了一个问题,其中提到使用jQuery来做到这一点:如何用jQuery将一个元素相对于另一个元素定位? jQuery是唯一的方法吗?可以使用CSS来完成吗?

I'm also aware of position:fixed to fix a div but I'm building a responsive website and I'd like to avoid that. I found a question here which mentions using jQuery to do it: How to position one element relative to another with jQuery? Is jQuery the only way to do it? Can it be done using CSS as well?

我在这里摆了一个小提琴: jsfiddle/19bdpgsf/.在小提琴中,我试图相对于 notparentdiv 定位 child2 元素,就像相对于 parent div定位它一样.可以仅使用CSS吗?

I've put up a fiddle here: jsfiddle/19bdpgsf/. In the fiddle, I'm trying to position the child2 element relative to the notparentdivjust like it has been positioned relative to the parent div. Is it possible using only css?

谢谢.

推荐答案

var nonparent = $('.notParent'); var position = nonparent.offset(); $('.child1').offset({ top: position.top, left: position.left });

.notParent { background-color: red; padding: 20px; } .child2 { background-color: yellow; } .child1 { background-color: green; } .parent { background-color: purple; }

<script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="notParent"> not parent div </div> <br/> <br/> <br/> <br/> <div class="parent"> parent <div class="child1">child1</div> <div class="child2"> child2 </div> </div>

更多推荐

使用CSS相对于不是其父级的另一个div定位一个div

本文发布于:2023-10-08 09:53:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:相对于   其父   CSS   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!