如何将div放在另一个div中的绝对位置?

Sty*_*bos 18 css css-position css3

例如,我想创建一个模板,如下图所示.

http://i.imgur.com/OneRsMw.png

如何将容器内的每个div定位到其绝对位置?我更喜欢不需要使用float属性.任何简短的例子将不胜感激.

Gab*_*oli 33

你可以使用absoluterelative定位.

例如

HTML

<div id="container" class="box">
    <div class="box top left"></div>
    <div class="box top center"></div>
    <div class="box top right"></div>

    <div class="box middle left"></div>
    <div class="box middle center"></div>
    <div class="box middle right"></div>

    <div class="box bottom left"></div>
    <div class="box bottom center"></div>
    <div class="box bottom right"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

#container{
    width:200px;
    height:200px;
    position:relative;
    border:1px solid black;
}
.box{
    border:1px solid red;
    position:absolute;
    width:20px;
    height:20px;    
}

.top{top:0}
.middle{top:50%;margin-top:-10px;/*half of the .box height*/}
.bottom{bottom:0}

.left{left:0;}
.center{left:50%;margin-left:-10px;/*half of the .box width*/}
.right{right:0;}
Run Code Online (Sandbox Code Playgroud)

演示 http://jsfiddle.net/gaby/MB4Fd/1/

(当然,您可以通过更改上/左/右/下值来调整实际定位到您的偏好)


adr*_*ift 6

position: relative;在容器上使用(<div>包含所有内容)并绝对定位子元素.容器内的子元素将相对于容器定位,因此根据您的需要放置所有内容非常容易.

然而,在大多数情况下使用定位来放置您的网站被认为是不好的做法.我建议使用浮动,即使您声称不想要,您将在不同的浏览器中具有更多的一致性.

如果你对浮动很困惑,请阅读这篇文章