21

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.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Stybos
  • 275
  • 1
  • 3
  • 10
  • 1
    You mean : you know nothing about html and want someone else to do a html template for you ? – Milche Patern Feb 25 '13 at 14:01
  • 17
    You're wrong my friend, it's css :) Try being more friendly next time, there's no single obstacle preventing you from that. – Stybos Feb 26 '13 at 09:05

2 Answers2

37

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)

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
7

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

Adrift
  • 58,167
  • 12
  • 92
  • 90