如何设置几个嵌套div的相对位置?

时间:2015-03-18 23:12:39

标签: html css

假设我有一些像div这样的div:

<div id="div0">
  <div id="div1"></div>
  <div id="div2"></div>
  <div id="div3"></div>
</div>

div0,div1和div3具有固定高度。现在我想让div2自动扩展,以便占用所有剩余空间。有没有办法实现这个目标? 请参阅此http://codepen.io/anon/pen/XJorMb作为示例,我希望蓝色框位于中间并占用所有剩余空间。

2 个答案:

答案 0 :(得分:1)

您可以使用flex执行此操作:

&#13;
&#13;
#fixedPanel {
  position:fixed;
  width: 350px;
  height:150px;
  border-style: solid;
  border-width: 5px;
  display:flex;
  flex-direction:column;
}
#div1 {
  height: 20px;
  border-style: solid;
  border-width: 1px;
  border-color: red;
}
#div2 {
  flex:1;
  border-style: solid;
  border-width: 1px;
  border-color: blue;
}
#div3 {
  height: 20px;
  border-style: solid;
  border-width: 1px;
  border-color: green;
}
&#13;
<div id="fixedPanel">
  <div id="div1"> 1 </div>
  <div id="div2"> 2 </div>
  <div id="div3"> 3 </div>
</div>
&#13;
&#13;
&#13;

display:table;

&#13;
&#13;
#fixedPanel {
  position:fixed;
  width: 350px;
  height:150px;
  border-style: solid;
  border-width: 5px;
  display:table;
  border-collapse:collapse;
}
#fixedPanel > div {
display:table-row;
}
#div1 {
  height: 20px;
  border-style: solid;
  border-width: 1px;
  border-color: red;
}
#div2 {
  height:100%;
  border-style: solid;
  border-width: 1px;
  border-color: blue;
}
#div3 {
  height: 20px;
  border-style: solid;
  border-width: 1px;
  border-color: green;
}
&#13;
<div id="fixedPanel">
  <div id="div1"> 1 </div>
  <div id="div2"> 2 </div>
  <div id="div3"> 3 </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

是的,对行使用tabletable-cell

http://jsfiddle.net/vrt2s232/1/

html, body {
    margin: 0;
    height: 100%;
}

#div0 {
    display: table;
    height: 100%;
}

#div0 > div {
    display: table-row;
}

#div1, #div3 {
    height: 100px;
    background: blue;
}

#div2 {
    background: red;
}
#div0 > div {
    display: table-cell;
}

#div1, #div3 {
    width: 100px;
    background: blue;
}

#div2 {
    background: red;
}

列:

http://jsfiddle.net/vrt2s232/