Ordering div using css | Innoraft Skip to main content

Search

31 Oct, 2013
2 min read

Ordering div using css

Image
Ordering div using css - Banner

As the heading suggests we will see how to order divs using css. Now one may ask why we need to use css and why not layout them in the desired order. Let us first understand why we need to use css to order divs. Let us start with an example, we need to create a layout with two sidebars - sidebar1, sidebar2 and a main content area - main-content. The two sidebars will contain blocks which are not related to the content displayed at the main area.We would like to arrange this two sidebars and main content area in one of the following three ways:

Now for the first layout we will layout our html in following way

<div class='page'>
<div class='sidebar1'> ... </div>
<div class='sidebar2'> ... </div>
<div class='main-content'> ... </div>
</div>
&lt;div class='page'&gt;<br />
&lt;div class='sidebar1'&gt; ... &lt;/div&gt;<br />
&lt;div class='sidebar2'&gt; ... &lt;/div&gt;<br />
&lt;div class='main-content'&gt; ... &lt;/div&gt;

 and will apply following css:

.page{
width:900px
}
.sidebar1, .sidebar2 {
width:200px;
float:left;
}
main-content{
width:500px;
float:left;
}

Now screen reader and robot will read this page as (as they dont see css ) contents of sidebar1 contents of sidebar2 content of main-area so they have to scroll a lot to see the content which they wanted to see on this page. So this is not good for a person using screen reader and even not for your page seo. Thats why main content should be kept at the top followed by other contents. Now i think this is clear as why to use css to order divs, not let us see how to use css to achieve this. For all the three layouts we will have same layout

<div class='page'>
<div class='main-content'> ... </div>
<div class='sidebar1'> ... </div>
<div class='sidebar2'> ... </div>
</div>

Now to achieve first layout we will use following css :

.page{
width:900px
}
.sidebar1, .sidebar2 {
width:200px;
float:left;
}
.main-content{
width:500px;
float:right;
}

Now that was straight and simple. Let us see css to achieve second layout

.page{
width:900px
}
.sidebar1{
width:200px;
margin-left:-200px;
float:left;
}
.sidebar2{
width:200px;
margin-left:500px;
float:left;
}
.main-content{
width:500px;
float:left;
margin-left:200px;
margin-right:-500px;
}

We have used negative margins to achieve desired result, in the similar way we can achieve the last layout using the following css:

.page{
width:900px
}
.sidebar1{
width:200px;
float:left;
}
.sidebar1{
width:200px;
float:left;
}
.main-content{
width:500px;
float:left;
}