When I apply the float property the bottom container goes up but not its content

Viewed 6

I have a container with two divs. If I apply float:left to the first, the second will go up occupying the remaining space to the right of the first. All good.

But if I apply a width to both the first and the second , something strange happens: The second goes up but places itself to the left of the floating element and also its content stays below.

.section{
        padding:30px 0;
        border: solid 2px blue;
        }

.row1{
        width:40%;
        height: 100px;
        border: solid 2px red;
        margin-left:21%;
        float: left;
        }

.row2{

         width:40%;
         height: 100px;
         border: solid 2px green;
         margin-left:0;
         padding:0;
         }    
<div class="section">

      <div class="row1">
          <p>This is a paragraph</p>
      </div>

      <div class="row2">
          <h1>This is a header</h1>
      </div>

</div>

Why is this happening? I expected the content of the second div to be to the right of the first div (as it happens when no width is set for the second div).

Thanks

1 Answers

It happens because you set row1 margin-left property 21%. Your row1 and row2 has 40% width, and row1 has 21% margin-left. 40% + 40% + 21% = 101%. So the floating element stays below. If you set row1's margin-left property less than 19%, it will work well. The result code must be looks like :

.row1{
        width:40%;
        height: 100px;
        border: solid 2px red;
        margin-left:19%;
        float: left;
        }

.row2{

         width:40%;
         height: 100px;
         border: solid 2px green;
         margin-left:0;
         float: left;
       } 
Related