我知道使用 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
发布评论