Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place div inside another div to absolute position?

Tags:

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

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

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.

like image 714
Stybos Avatar asked Feb 25 '13 13:02

Stybos


People also ask

How do you position a div based on another div?

You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).

Can you nest a div inside another div?

Yes, a div inside div works.

Can you have div within div?

You can put a div inside an div but once you do that you can only put block elements (like divs) inside the first div. And if you put an inline element inside an div only inline elements can go inside the div.


2 Answers

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)

like image 94
Gabriele Petrioli Avatar answered Oct 21 '22 12:10

Gabriele Petrioli


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

like image 22
Adrift Avatar answered Oct 21 '22 12:10

Adrift