How CSS containers overlap and float on each other

We all know containers that web designers or even programmers used on the web! If we ignore all the coding you will find that all these things are actually done by CSS! i created two container with the following code,

<html>
<head>

<style>
#box1 {
width:450px;
height:338px;
background:#23e;
float: left;

}
#box2 {
width:450px;
height:338px;
background:#000;
padding: 5px 5px;
margin: 10px 10px;
position: absolute;
float: left;
z-index: 1;
}
</style>
<script>

</script>
</head>

<body>
<div id='box1'></div>
<div id='box2'></div>
</body>
</html>

You can have a look at the example HERE, notice that the black box is overlapping the blue box? The blue box has the CSS of box1 while the black box has the CSS of box2. The reason why it is overlapping was because of the following declaration,

<pre class="brush: php; title: ; notranslate" title="">  position: absolute;
 float: left;
 z-index: 1;

position absolute must be there to tell the page that the position must absolutely be obey and only with this declaration, z-index can be used. z-index tells the box to go 1 up (float upward) while negative means it will go downwards. So if i want the blue box to be overlapping the black instead, i will place z-index:-1, this way it will go below the blue box. While float:left tells the box to appear on the left side. If i do not want them to be overlapped, i will remove the declaration of position:absolute, this way z-index will not be valid and it will become side by side as shown HERE.

CSS is capable of styling and perform layout for your site! If i have another box name box3 and wanted the box to be place below the two box what do i do? assume the code declaration is as below,

<pre class="brush: php; title: ; notranslate" title=""><html>
<head>

<style>
#box1 {
width:250px;
height:338px;
background:#23e;
float: left;

}
#box2 {
width:250px;
height:338px;
background:#000;
padding: 5px 5px;
margin: 10px 10px;
float: left;

}

#box3 {
width:250px;
height:338px;
background:#23e;
float: left;
clear: left;
}
</style>
<script>

</script>
</head>

<body>
<div id='box1'></div>
<div id='box2'></div>
<div id='box3'></div>
</body>
</html> 

in box3, there is a new declaration, clear:left. This tells the page that box3 left side shall not have any other element which makes box3 move down to a new line. Click Here for example.Notice that this kind of layout is called a fixed layout where the boxes width cannot be more than the user screen width. If a liquid layout is being applied, the boxes will resize according to the user screen size. In order to change the fixed layout to a liquid layout, we just have to change the width to % instead of px.

Share