简体   繁体   English

如何使用Float而不是绝对定位将多个Div堆叠在一起?

[英]How can I have multiple Divs stack on top of each other using Float and not absolute positioning?

I'm rewriting everything and moving away from absolute positions and instead using floats to position things the way I want them. 我正在重写所有内容并远离绝对位置,而是使用浮动来按照我想要的方式定位事物。

The question now is how can I float multiple divs on top of each other? 现在的问题是如何将多个div放在一起? The user will be able to switch between these divs somehow. 用户将能够以某种方式在这些div之间切换。

Thanks 谢谢

Edit: The reason I'm moving away from absolute position is that I want my div to still be a child of its parent. 编辑:我离开绝对位置的原因是我希望我的div仍然是其父母的孩子。 ie if my div gets extended I want the parent div to get extended also. 即如果我的div得到扩展,我希望父div也得到扩展。

float does not overlap with other floated objects in the same container. float不与同一容器中的其他浮动对象重叠。 See here for an example of three successive floated objects to see how they don't overlap. 请参阅此处查看三个连续浮动对象的示例,以了解它们如何不重叠。

If you want objects to overlap, you will want/need to use absolute positioning. 如果希望对象重叠,则需要/需要使用绝对定位。 You can use positioning relative to the parent object by setting the parent to position:relative; 您可以通过将父级设置为position:relative;来使用相对于父对象的position:relative; and the child to position: absolute; 和孩子的position: absolute; . See here for an example of overlaping objects with absolute positioning relative to the parent. 请参阅此处以获取具有相对于父级的绝对定位的对象的重叠示例。

If, you're trying to only have one of these objects actually display at a time, then just set the non-displayed objects to display: none and they will take no space in the page layout. 如果,您尝试一次仅实际显示其中一个对象,则只需将未显示的对象设置为display: none ,它们将不会在页面布局中占用任何空间。 You won't need to use float or absolute positioning. 您不需要使用浮动或绝对定位。

I'm inexperienced in CSS selectors, but I'm sure you can find something that works better than naming each class specifically: 我在CSS选择器方面缺乏经验,但我确信你能找到比专门命名每个类更好的东西:

http://jsfiddle.net/aJqb2/ http://jsfiddle.net/aJqb2/

HTML: HTML:

<div class="over1"></div>
<div class="over2"></div>
<div class="over3"></div>

CSS: CSS:

div{
    height:50px;
    width:150px;

    float:left;
}
.over1{
    background-color:blue;
}
.over2{
    margin-top:10px;
    margin-left:-10px;
    background-color:green;
}
.over3{
    margin-top:20px;
    margin-left:-10px;
    background-color:orange;
}

I don't see how you are going to have users switch between the DIVs without using JavaScript. 我不知道如何让用户在不使用JavaScript的情况下在DIV之间切换。

Perhaps, leave the first div with the default static layout and display none for the others. 也许,将第一个div保留为默认静态布局,并为其他布局显示none。 Use JavaScript to show only one div at a time. 使用JavaScript一次只显示一个div。

You can use float: left; 你可以使用float: left; , but personally I find it easier to use display: inline-block; ,但我个人觉得使用display: inline-block;更容易display: inline-block; instead. 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM