css – 如何将div放在另一个div到绝对位置?

例如,我想在下面的图片中创建一个模板.

你如何将容器中的每个div放在绝对位置?我宁愿不需要使用float属性.任何简短的例子将不胜感激.

解决方法

您可以使用绝对和相对定位.

例如

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>

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;}

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

(您可以通过更改顶部/左/右/底部值来调整您的偏好的实际位置)

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效