2

Say I have three boxes to nest. A, B, and C. I want to have them nested in an way that C resides within, but positions relative to B, B resides within but positions relative to A, and A positions relative to the browser. I understand in common cases, where I only need to nest two of them, say B within A, I can make A position:relative and B position:absolute. In this way, I embed box B within A and adjust its positions within A's area. However in the case of three boxes(or even more ), How can I have them placed in such a way?

In picture. my desired effect would be as following. So that B is limited to the area within A, and C is limited within area of B

enter image description here

4

3 回答 3

1

Use position:relative; on the outer parent - in your case A.

Then place all other divs using position:absolute and set the offset using top, bottom, left and right properties. Each <div> will be automatically relative to it's direct parent. Working jsFiddle example

HTML:

<div id="a">
    <div id="b">
        <div id="c"></div>
    </div>
</div>

CSS:

#a{
    position:relative;
    width:200px;
    height:200px;
    background:red;
}

#b{
    position:absolute;
    top:75px;
    left:100px;
    background:cyan;
    width:75px;
    height:100px;
}

#c{
    position:absolute;
    background:white;
    top:10px;
    left:10px;
    width:40px;
    height:40px;
}
于 2013-08-22T13:23:37.493 回答
0

by setting the position absolute, your positioning it to the closest positioned parent.

from MDN:

position it at a specified position relative to its closest positioned ancestor

which means that if "A" and "B" sets to absolute, its the same as "A" sets to relative and "B" sets to absolute like in your example.

于 2013-08-22T13:30:32.037 回答
0

It could be built with css calc:

Example how it looks like

Example codesandbox.io

HTML

<div id="div1" class="div1 borderBackgr_1" onClick="handleEvent('div1')">
  div1
  <div id="div2" class="div2 borderBackgr_2" onclick="handleEvent_1('div2')">
    div2
    <div id="div3" class="div3 borderBackgr_3">
      div3
    </div>
  </div>
</div>

CSS

.div1 {
  text-align: center;
  position: relative;
  margin: 1em auto;
  width: 25em;
  height: 20em;
}

.div2 {
  text-align: center;
  position: absolute;
  left: calc((100% - 20em) / 2);
  top: calc((100% - 15em) / 2);
  width: 20em;
  height: 15em;
}

.div3 {
  text-align: center;
  position: absolute;
  left: calc((100% - 15em) / 2);
  top: calc((100% - 10em) / 2);
  width: 15em;
  height: 10em;
}

.borderBackgr_1 {
  border: solid 1px black;
  background: pink;
}

.borderBackgr_2 {
  border: solid 1px blueviolet;
  background: silver;
}

.borderBackgr_3 {
  border: solid 1px green;
  background: orange;
}
于 2018-10-02T00:34:04.577 回答