How to place div inside another div to absolute position?

拈花ヽ惹草 提交于 2019-12-17 22:39:53

问题


For instance, I would like to create a template like in the image below.

How do you position each div inside the container to its absolute position? I would prefer without needing to use float-attributes. Any short examples would be appreciated.


回答1:


You can use absolute and relative positioning.

for example

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

Demo at http://jsfiddle.net/gaby/MB4Fd/1/

(ofcourse you can adjust the actual positioning to you preference, by changing the top/left/right/bottom values)




回答2:


Use position: relative; on the container (a <div> containing all the content) and absolutely position the child elements. The child elements inside the container will be positioned relative to the container so it would be pretty easy to lay everything out to your needs.

However, It's considered bad practice to use positioning in most circumstances to lay your site out .. I'd suggest using floats even though you claim to not want to, you'll have much more consistency across different browsers.

Read this article if you're confused about floats



来源:https://stackoverflow.com/questions/15068624/how-to-place-div-inside-another-div-to-absolute-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!