【问题标题】:Absolute divs next to eachother彼此相邻的绝对 div
【发布时间】:2015-05-18 16:21:02
【问题描述】:

在我的 html 页面中,我在一个容器 div 中有两个 div。两个内部 div 有一个“位置:绝对”。因为它们必须放在容器 div 的左下角。

当容器 div 只有一个内部 div 时,这很有效。但是当我添加第二个 div 时,第二个 div 被放置在第一个内部 div 的顶部。这当然是有道理的。但现在我正试图找到一种方法让它们彼此相邻而不是彼此重叠。

生成内部 div。所以我不能手动为他们添加 ID。他们只有一个类名。

Example:

<div id="container">
    <div class="icon">ICON1</div>
    <div class="icon">ICON2</div>
</div>
#container {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

.icon {
    position: absolute;
    bottom: 0;
    left: 0;
    border: 1px solid green;
}

有人知道如何解决这个问题吗?

【问题讨论】:

  • 你可以让它们相对定位,因为它们会保持相对于父(容器)元素的布局
  • 如何将每个 ICON 放在一个 'li' 中,而不是 'div' 元素?样式化列表项就非常灵活和简单!
  • 只使用第一个孩子/最后一个孩子,看我的回答

标签: html css


【解决方案1】:

在包装元素上使用绝对定位而不是每个单独的图标,然后您可以在该容器中浮动或放置您喜欢的图标:

<div id="container">
    <div class="icon-wrapper">
      <div class="icon">ICON1</div>
      <div class="icon">ICON2</div>
    </div>
</div>
#container {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid red;
}
.icon {
    border: 1px solid green;
    float:left;
}
.icon-wrapper {
    position: absolute;
    bottom: 0;
    left: 0;
}

演示:http://jsfiddle.net/sYGfq/3/

【讨论】:

    【解决方案2】:

    如果只有 2 个,你可以在 css 中使用 :first-child 或 :last-child,不需要添加额外的 html。几行 css 就可以搞定它

    这里的例子http://jsfiddle.net/sYGfq/6/

    最后一个孩子的 CSS

    .icon:last-child {
        left: 200px;
        border: 1px solid green;
    }
    

    【讨论】:

    • 谢谢,但我认为 IE7 不支持 last-child(不确定 IE8)。
    • 然后使用first-child,支持其中一个,见IE 7中的jsfiddle.net/sYGfq/8
    • @Huangism 你在 IE 中检查过吗,因为其中一个从容器 div 中掉了出来。此外,当您有 3 个或更多图标时,“第一个孩子”有什么用。
    • @Vivendi 我在 IE 7 中做了第一个孩子,但在 VM 上。它失败了,因为我将 left 设置为 200。在他的问题中,他只提到了 2,我的回答也是如此。如果有更多图标,则问题并不明显
    【解决方案3】:

    将两个 div 放入表格中的单独单元格中,从表格中删除所有边框和填充,并将其绝对定位在父 div 的左下角。

    <div id="container">
    <table class="none" id="table1">
    <tr class="none">
    <td class="none">
    <div class="icon">ICON1</div>
    </td>
    <td class="none">
    <div class="icon">ICON2</div>
    </td>
    </tr>
    </table>
    </div>
    

    #container {
        position: relative;
        width: 200px;
        height: 200px;
        border: 1px solid red;
    }
    
    .icon {
        border: 1px solid green;
    }
    
    .none {
        border: 0;
        padding: 0;
    }
    
    #table1 {
        position: absolute;
        bottom: 0;
        left: 0;
    }
    

    快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多