将两个绝对div彼此相邻放置而不重叠

时间:2016-02-20 14:08:40

标签: html css

我有这个设置:

<div id="container">

   <div class="left"> 1 </div>

   <div class="left"> 1 </div>

   <div class="right"> 2 </div>

</div>

我希望使用leftposition:absolute div放在彼此后面。工作正常。

我希望通过添加rightright:0 div置于右侧。工作正常。

问题是leftright div相互重叠。我不想要这个。我希望左div不与右div的内容重叠。

我无法为任何一个div设置固定宽度。

请参阅此jsFiddle以了解该问题。

这是我的CSS:

#container {
    width:100%;
    position:relative;
}

.left {
  position:absolute;
  background:yellow;
}

.right {
  position:absolute;
  background:green;
  right:0;
}

1 个答案:

答案 0 :(得分:2)

您可以使用 Flexbox position: absolute

执行此操作

#container {
  width:100%;
  display: flex;
  align-items: flex-start;
}

.left-wrapper {
  position: relative;
  flex: 1;
}

.left {
  background: yellow;
  position: absolute;
  width: 100%;
}

.left:last-child {
  opacity: 0.5;
  background: lightblue;
  margin-top: 10px;
}

.right {
  background:green;
  white-space: nowrap;
}
<div id="container">
  <div class="left-wrapper">
     <div class="left"> Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world </div>
     <div class="left">Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world</div> 
  </div>
  <div class="right">Don't overlap please</div>
</div>

CSS表格position: absolute

#container {
  display: table;
}

.left-wrapper {
  display: table-cell;
  position: relative;
  vertical-align: top;
  width: 100%;
}

.left {
  background: yellow;
  position: absolute;
  width: 100%;
}

.left:last-child {
  margin-top: 10px;
  opacity: 0.5;
  background: lightblue;
}

.right {
  background: green;
  display: table-cell;
  vertical-align: top;
  white-space: nowrap;
}
<div id="container">
  <div class="left-wrapper">
     <div class="left"> Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world </div>
     <div class="left">Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world</div> 
  </div>
  <div class="right">Don't overlap please</div>
</div>