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

标签 html css

我有这样的设置:

<div id="container">

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

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

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

</div>

我想使用 position:absoluteleft div 放置在彼此后面。工作正常。

我想通过添加 right:0right 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;
}

最佳答案

您可以使用Flexboxposition: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>

关于html - 将两个绝对 div 彼此相邻放置而不重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35524388/

相关文章:

html - 把两个 div 一个挨着一个放

javascript - 在一行中自动调整不同大小的图像

javascript - 使元素自动并重复向上滚动

css - ui-select + 父 div 中的选项可见性问题有 overflow-x 滚动

css - Div 的高度得到扩展,但元素出现在 div 的工作空间之外

javascript - 如何让 javascript 函数在 php 表中工作?

html - div的过滤器适当性如何不会影响div内部的文本?

html - 拉伸(stretch)右浮动 div 宽度?

java - 如何从 Java 验证 HTML?

javascript - 为什么在 HTML5 中使用 &lt;script&gt;&lt;/script&gt; 而不是 &lt;script/>?