Floats
Floats are used to rearrange how elements in a web page are displayed. For understanding floats you need to understand how a natural float looks like.
1 2 3 4 5 |
<div class=”element1”> <p>Block level Element 1</p> <h1> Block level Element 2 <span>This is inline content <span> </h1> <h3> Block level Element 3 </h3> </div> |
Block level element takes 100 % of the width and are aligned below each other in a sequence.
Inline element displayed within the line.
By using float property we can align elements to right or left of its container. This is a change to natural flow and the elements below the floated element can be deranged.
Let us discuss float property with an example.
1 2 3 4 5 6 7 8 9 10 11 |
<div class="wrapper-element"> <img src="http://happinessmultiplied.com/wp-content/uploads/2018/02/focused-reading.jpg" width="90" height="90"> <p>Content Here...</p> </div> <style> img{ float:left; } </style> |
By floating an image to the left the element following it will move up and flow next to element. If the content is longer than the image the remaining text will flow below it.
The main problem is all element below the floated element will flow around it as long there is a space.
So we will apply some CSS to it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<div class="wrapper-element"> <img src="http://happinessmultiplied.com/wp-content/uploads/2018/02/focused-reading.jpg" width="90" height="90"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting </p> <h1> This Is Heading </h1> </div> <style> .wrapper-element{ background:lightblue; } img{ float:left; margin-right:20px; } </style> |
Edit this example here: https://jsfiddle.net/kritika90/x4j06w2j/
Clearing Floats:
To return natural page-flow floats must be cleared. In the above example if we want h1 not to float with the image we apply the clear property to h1. This will return it back to natural stacking flow.
1 2 3 |
h1{ clear:both;/* Clear any float left or right*/ } |
Float also effects the parent element. The parent element will not recognize the height of floated element. If all the content within the parent element is floated then its height will become zero. When there is no element left in the parent element to clear the float parent element will have to self-clear.
Ways to Self-clear float:
Use Overflow property
1 |
overflow:hidden or overflow:auto |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="parent"> <div class="floated1">Left Floated Element</div> <div class="floated2"> Right Floated Element</div> </div> .floated1{ float:left; } .floated1{ float:right; } .parent{ overflow:hidden; /* OR */ overflow:auto; } |
Other use of Overflow:
Generally, overflow is used when a specific height is given to an element.
Overflow: hidden Will clip the content to height specified
overflow: auto add a scrollbar