使用CSS相对于不是其父级的另一个div定位一个div [英] Position a div relative to another div which is not its parent using CSS

查看:58
本文介绍了使用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?

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

I've put up a fiddle here: http://jsfiddle.net/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="https://ajax.googleapis.com/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆