Archive

Posts Tagged ‘CSS’

Fix for floating div

April 3, 2016 Leave a comment

First refer CSS snippet given below which is about to be used while discussing this problem & solution.

div {border:#000 1px solid; width: 50px;}
.L {float:left;}
.R {float:right;}

Let’s start.

Case 1

< div class="L">1< / div >
< div >Amit Gupta< / div >
< div class="R">2< / div >
< div >articlestack.wordpress.com< / div >

Result :

1
Amit Gupta
2
articlestack.wordpress.com

Explanation:

First Div will let its upcoming elements take place in its right ie div containing “Amit Gupta” word. This is the basic property of a floated div. But a simple DIV never let any upcoming element take place to its right or left. So the 3rd div is shifted to next line. Similar to First DIV, Third DIV will also let its upcoming element place it’s left.

Doubt : Why 4th DIV is not starting from starting of line?

SubCase 1

<div> Container
<div> child </div>
</div>

Output

Container

child

 

SubCase 2

<div> Container
<div class="L"> child </div>
</div>

Output

Container

child

 

Explanation:

Height of a simple DIV with default width 100% is increased by the height of its element. On the opposite side, Height of floated DIV may increased and can pop out from its container on y-axis. So it doesn’t let any other element draw on y-axis.

Revised case 1

<div class="L" style="width: 150px">1</div>
<div>Amit Gupta</div>
<div class="R">2</div>
<div>articlestack.wordpress.com</div>

Output:

1
Amit Gupta
2
articlestack.wordpress.com

Solution:

Use of clear property removes floating effect and let other element flow in normal way. For example;

<div class="L">1</div>
<div>Amit Gupta</div>
<div style="clear: left"></div>
<div class="R">2</div>
<div>articlestack.wordpress.com</div>

Output

1
Amit Gupta
2
articlestack.wordpress.com

Now if you increase the height of floated DIV it doesn’t affect upcoming elements.

<div class="L" style="width: 150px">1</div>
<div>Amit Gupta</div>
<div style="clear: left"></div>
<div class="R">2</div>
<div>articlestack.wordpress.com</div>

Output:

1
Amit Gupta
2
articlestack.wordpress.com

Warning:

For Browser’s compatibility

  1. Never use clear property with DIV using for displaying contents like
  2. Try to use clear:both instead of clear:left or clear:right.
Advertisements
Categories: Other, Tutorial Tags:
%d bloggers like this: