0

I'm recently learning web development and get confused with the concept of floating. Here is my code.

.test {
  background-color: red;
  height: 200px;
  width: 200px;
  float: left;
}

.test1 {
  background-color: blue;
  height: 200px;
  width: 200px;
}
<div class="test">Box 1</div>
<div class="test1">Box 2</div>

The result in browser is here

I just don't know why text Box 2 is placed below the red box but with the blue box moved up and covered by the red box. To my understanding, text Box 2 should move up as well and then covered by the red box.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
DP1024
  • 1
  • 1
  • I added many duplicate explaining different tricky cases related to float. Follow them carefully and you will understand what is happening here – Temani Afif Apr 02 '20 at 08:27

1 Answers1

-1

As you can see on your screenshot, the static element does got an effect from the floating element before. The blue box isn't blue anyway because its overflowing the wrapping container (here the <body>). If you want to put both boxes beside add the float on every element which should be in the "row".

Check "The clearfix Hack" on w3schools css float. If you use the DevTools of your Browser, you see the overflowing like the description of this link of w3schools. For a better testing I have added a third green box to your example:

.test_01 {
  background-color: red; 
  height: 100px;
  width: 100px;
  float: left;
}

.test_02 {
  background-color: blue;
  height: 100px;
  width: 100px;
}

.test_03 {
  background-color: green;
  height: 100px;
  width: 100px;
}
<div class="test_01">Box 01</div>
<div class="test_02">Box 02</div>
<div class="test_03">Box 03</div>

At least you should clear every float you used before. If you are developing a grid system, you should better use the flex-box. Bootstrap changed the grid system from float to display: flex from version 3 to version 4. You can find an explanation of display: flex on w3schools or here

UfguFugullu
  • 2,107
  • 13
  • 18