【问题标题】:CSS Positioning: How to make 2 overlapping divs and then 1 more div to the right of the overlapping divsCSS 定位:如何制作 2 个重叠的 div,然后在重叠 div 的右侧再制作 1 个 div
【发布时间】:2014-06-19 15:56:45
【问题描述】:

我如何定位 2 个重叠的 div 加上第三个 div 就在这些重叠 div 的右侧(但第三个没有一直向右浮动)?

<div id=one>I overlap id=two.</div>

<div id=two>I overlap id=one.</div>

<div id=three>I am just to the right of one and two.</div> 

想要的布局是:

|一重叠二 |三 |

http://i.imgur.com/4CMNaUh.png

我知道我可以使用 position:relative 的包装 div 重叠前 2 个 div,并将 div 一个和两个设置为 position:absolute

<div id="wrapper">

    <div id=one>I overlap id=two.</div>

    <div id=two>I overlap id=one.</div>

</div>

#wrapper{position:relative;}
#one,#two{position:absolute;}

但是我怎样才能让 div id=three 在重叠 div 1 和 2 的右侧?

到目前为止我得到了什么:http://jsfiddle.net/justAsking/cXrBA/

【问题讨论】:

标签: html css


【解决方案1】:

解决办法如下:

http://jsfiddle.net/cXrBA/2/

HTML

<div class="wrapper">

<div class="one"></div>
<div class="two"></div>
<div class="three"></div>

</div>

CSS

.wrapper {
    padding-left: 100px;
    width: 100px;
    height: 100px;
    position: relative;
}
.one , .two {
    width: 100px;
    position: absolute;
    left: 0;
}
.one {
    background-color: blue;
    height: 50px;
    top: 0;
    z-index: 1;
}
.two {
    background-color: red;
    height: 100px;
    top: 0;
}
.three {
    background-color: green;
    width: 100px;
    height: 100px;
}

【讨论】:

  • 谢谢...这行得通!我是否正确理解绝对定位的元素已从文档流中取出,因此我将始终必须对包装器宽度进行硬编码以获得所需的对齐方式?还是有另一种方法可以在没有硬编码宽度的情况下获得所需的对齐方式?
  • 不,包装宽度的硬编码不是强制性的。我做了硬编码只是为了说明目的。您可以从.wrapper.three 中删除width 属性,以便第三个div 占用可用的宽度空间。
【解决方案2】:

给第二个 div 一个负边距-left;

http://jsfiddle.net/HXH76/

div {
    display: inline-block;
}

#one {
    background: hsla(0,100%, 50%, 0.50);
}

#two {
    background: hsla(90,100%, 50%, 0.50);
    margin-left: -40px;    
}

#three {
    background: hsla(180,100%, 50%, 0.50);
}

【讨论】:

  • 那么 display:inline-block 用于所有三个 div,然后使用 margin-left 将 div-2 移动到 div-one 的顶部?我看到你硬编码-40px。如何在不硬编码像素数的情况下设置 margin-left?
  • 那么你希望它掩盖多少?什么将决定这一点?
  • #one & #two 大小相同(它们完全重叠)。我希望 #three 位于 #one+#two 的右侧(但 #three 不重叠 #one+#two。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多