Position element inside absolute parent with respect to grandparent

南笙酒味 提交于 2019-12-03 07:44:17

问题


I have child element which need to be positioned absolute with the grandparent. The problem is that the parent is also positioned absolutely.

I can't use JavaScript. How can I achieve this with just pure CSS?

JSFiddle Demo

<div class="col-md-6 gp">
    <div class="col-md-4 p">
        <div class="col-md-2 c"> position me w.r.t to .gp</div>
    </div>
</div>
.gp { height : 200px; position: relative; }

.p {
    height : 100px; width: 250px;
    position :absolute;
    top : 50px; left: 50px;
}

.c { position: absolute; height: 50px; }

回答1:


If supporting Internet Explorer 8 (and below) is not a concern, we could achieve that by pure CSS. Here is what you should know about CSS Transforms:

6 The Transform Rendering Model

For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

Hence, we add a transform with a value other than auto to the grandparent element, we will be able to use fixed positioning place the child element with the respect of the grandparent element which is creating the containing block.

EXAMPLE HERE

For instance:

.grandpa {
  position: relative;
  height: 500px;

  -webkit-transform: rotate(0deg);
  -moz-transform: rotate(0deg);
  -ms-transform: rotate(0deg);
  -o-transform: rotate(0deg);
  transform: rotate(0deg);
}

.dad {
  position: absolute;
  width: 250px; height: 250px;
  bottom: 4em; left: 4em;
}

.son {
  position: fixed; /* This will be positioned with the respect to the grandpa
                      rather than the viewport */
  width: 100px; height: 100px;
  top: 2em; right: 2em;
}

Also, CSS Legendary Eric Mayer has written an article about this:

Un-fixing Fixed Elements with CSS Transforms

A transformed element creates a containing block even for descendants that have been set to position: fixed. In other words, the containing block for a fixed-position descendant of a transformed element is the transformed element, not the viewport.




回答2:


I haven't really understand what you are asking, but i've edit your css:

.gp {
   height : 200px;
   border : 1px solid red;
 }
 .p {
   height : 100px;
   width: 200px;
   border : 1px solid blue;
   position: absolute;
   top : 50px;
   left : 50px
}
.c {
    height : 50px;
    border : 1px solid green;
    position: absolute;
    top:0;
    left:0;
}

you've wrote positioned and not position. Tell me if now it works



来源:https://stackoverflow.com/questions/25768069/position-element-inside-absolute-parent-with-respect-to-grandparent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!