Position an element relative to another that is not its parent

时间:2019-04-17 02:28:33

标签: javascript html css reactjs

Considering that components such as dialogs, modals, tooltips, etc. should be of higher stacking index than any other elements in an HTML page, I placed these components in an immediate sibling of root element where all the other elements are placed. React developers will quickly recognize this and they'll know that I'm trying to use React Portals. You can visualize it here:

<body>
  <div id="root">
    // ----- other elements -----
    <div id="supposed-parent" />
    // ----- other elements -----
  </div>
  <div id="dialog-container">
    <div id="supposed-child" />
  </div>
</body>

So, how can I position #supposed-child next or beside #supposed-parent? Any help would be appreciated.

1 个答案:

答案 0 :(得分:1)

我认为使用纯CSS不可能做到这一点。但是,只需编写一些脚本,我们就可以实现这一目标。以假定父母的左偏和顶部为准,并将其应用于假定孩子。子元素应为绝对定位元素。检查以下示例,希望它对您有用。

即使假定孩子(黄色框)与假定父母无关,但它始终与假定父母的左上角对齐。

function offsetCalculate(){
    var parentTop = $('#supposed-parent').offset();
    var parentLeft = $('#supposed-parent').offset();
    $('#supposed-child').css({
        'top':parentTop.top,
        'left': parentLeft.left
    });
}
$(document).ready(function () {
    offsetCalculate();
});
$(window).resize(function(){
    offsetCalculate();
});
#supposed-child{
    position: absolute;
    background: yellow;
    border-radius: 5px;
    padding: 10px;
    z-index: 999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root">
    <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor libero, euismod et nisl eu, imperdiet elementum neque. Praesent aliquet non tellus sed blandit. Ut vitae velit eget turpis ornare convallis. Quisque nec felis eget mi vestibulum luctus eu non dui.</h1>
    <div id="supposed-parent">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor libero, euismod et nisl eu, imperdiet elementum neque. Praesent aliquet non tellus sed blandit. Ut vitae velit eget turpis ornare convallis. Quisque nec felis eget mi vestibulum luctus eu non dui. Pellentesque eget commodo tellus. Curabitur a dolor est. Integer dapibus lectus nec mi luctus, ac ornare ex auctor. Donec vel nisi nulla. Mauris maximus egestas nunc ut egestas. Suspendisse id leo nec elit consectetur interdum. Ut purus nibh, tristique quis est vel, ultrices blandit nibh. Aenean nibh justo, mattis sed vulputate quis, efficitur eu mauris. Sed vel vulputate metus, et dictum arcu. In ornare nisl vitae purus elementum, quis egestas dolor volutpat. In velit nisi, posuere in urna non, feugiat luctus enim.
    </div>

</div>
<div id="dialog-container">
    <div id="supposed-child" >This is a popup</div>
</div>