Tuesday, September 16, 2014

Placing two DIVs horizontally one after another in same row

In this tutorial I am going to show you how to place two DIVs near each other one after another as in below image.
Note that in this tutorial I am using inline styles so that anyone can understand easily.

If we just add two DIVs in to a HTML page those will be displayed in two rows as below.

<div style="border:solid 2px green;width:200px;height:100px;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;">
    Second DIV
</div>



Now lets see how we can place the first these DIVs side by side. It is really easy. What you need is to add the style "float:left" to both DIVs.

<div style="border:solid 2px green;width:200px;height:100px;float:left;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;float:left;">
    Second DIV
</div>



Wow! seems working. Wait...
Now add a third DIV after these two DIVs as below.

<div style="border:solid 2px green;width:200px;height:100px;float:left;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;float:left;">
    Second DIV
</div>
<div style="border:solid 3px red;width:250px;height:150px;">
    Third DIV
</div>

Output will be as below.

Oops.. something has gone wrong. You can see the third DIVs is overlapped with the first two DIVs. Actually this is the expected behavior with "float:left" style.
Any content you add after a component which is floated, will be overlapped with the floated components.
How can we overcome this issue? Just add another DIV after the first two DIVs and set the style of that DIV to "clear:both".
Any content you put after this DIV will not be overlapped.

<div style="border: solid 2px green; width: 200px; height: 100px; float: left;">
    First DIV</div>
<div style="border: solid 2px blue; width: 200px; height: 100px; float: left;">
    Second DIV</div>
<div style="clear: both;" />
<div style="border: solid 3px red; width: 250px; height: 150px;">
    Third DIV
</div>

Now you get the desired output.



No comments:

Post a Comment