In its simplest use, the float property can be used to wrap text around images.
Example
img {
float: right;
}
Example
img {
float: left;
}
img {
float: none;
}
div {
float: left;
padding: 15px;
}
.div1 {
background: red;
}
.div2 {
background: yellow;
}
.div3 {
background: green;
}
When clearing floats, you should match the clear to the float: If an element is floated to the left, then you should clear to the left. Your floated element will continue to float, but the cleared element will appear below it on the web page.
Example
This example clears the float to the left. Here, it means that the <div2> element is pushed below the left floated <div1> element:
div1 {
float: left;
}
div2 {
clear: left;
}
Example
.clearfix {
overflow: auto;
}
The overflow: auto clearfix works well as long as you are able to keep control of your margins and padding (else you might see scrollbars). The new, modern clearfix hack however, is safer to use, and the following code is used for most webpages:
Example
.clearfix::after {
content: "";
clear: both;
display: table;
}
With the float property, it is easy to float boxes of content side by side:
Example
* {
box-sizing: border-box;
}
.box {
float: left;
width: 33.33%; /* three boxes (use 25% for four, and 50% for two, etc) */
padding: 50px; /* if you want space between the images */
}
What is box-sizing?
You can easily create three floating boxes side by side. However, when you add something that enlarges the width of each box (e.g. padding or borders), the box will break. The box-sizing property allows us to include the padding and border in the box's total width (and height), making sure that the padding stays inside of the box and that it does not break.
The grid of boxes can also be used to display images side by side:
Example
.img-container {
float: left;
width: 33.33%; /* three containers (use 25% for four, and 50% for two, etc) */
padding: 5px; /* if you want space between the images */
}
Example
.box {
height: 500px;
}
However, this is not very flexible. It is ok if you can guarantee that the boxes will always have the same amount of content in them. But many times, the content is not the same. If you try the example above on a mobile phone, you will see that the second box's content will be displayed outside of the box. This is where CSS3 Flexbox comes in handy - as it can automatically stretch boxes to be as long as the longest box:
Example
Using Flexbox to create flexible boxes:
10 videos|41 docs|23 tests
|
|
Explore Courses for Class 6 exam
|