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.
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 ).
Yes, a div inside div works.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With