css溢出和左边空白



我在一个父div中有三个div溢出:隐藏;我想展示第三个。所以我想,我可以给第一个div一个左边的空白,另外两个将向左移动。

<div style="width:1000px;background:red;overflow:hidden;height:50px;">
    <div style="width:1000px;height:50px;float:left;margin-left:-2000px;">
    1
    </div>
    <div style="width:1000px;height:50px;float:left;">
    2
    </div>
    <div style="width:1000px;height:50px;float:left;">
    3
    </div>
</div>

但它显示了第二个div。但如果我加上左边的边距:-1000px;到第二个div并替换左边的边距:-2000px;第一个div上的-1000px将正常工作。我不明白为什么。

当您将-1000px设置为div时,此div不再处于相对位置,因此另一个div将占据与父div的相对位置。

Fiddle测试示例:http://jsfiddle.net/FvBwC/5/

<div class="parent">    
    <div class="one">1</div>
    <div class="two">2</div>
    <div class="three">3</div>
</div>
.parent { width:1000px; background:red; overflow:hidden; height:50px;  }
.one, .two, .three { width: 1000px; height: 50px; float: left; }
.one { background: blue; margin-left: -1000px; } 
.two { background: yellow; margin-left: -1000px; }
.three { background: green; }

但为了获得更好的解决方案,我会选择display:CSS中的none或jQuery中的.hide()。

因为第一个div被移动到父元素外的左侧2000 px。这基本上将它从父对象内其他所有对象的相对位置中"移除"。换句话说,剩下的元素被放置在父元素内部,就好像第一个div从未出现过一样。Div 2的位置相对来说就像它是父元素中的第一个元素一样,即位于左侧:0。如果您想将div 2定位在父级之外,则需要明确定义其位置(如设置其边距:-1000px)。

为了更清楚地了解发生了什么,请将3个子div设置为100px的宽度,使父div保持在1000px。再玩一些边缘游戏。你应该看看发生了什么。

EDIT:如果您只想显示一个特定的div并隐藏另外两个,那么只需将另外两个设置为display:hide即可。

最新更新