Search code examples
htmlcsscss-float

Why does the float-right element not go all the way to the top?


I know that this happens, but would like clarification as to why, as I'm trying to get a better understanding of the float mechanic

Given this HTML

<div class="wrapper">
  <div class="inner first">1</div>
  <div class="inner second">2</div>
  <div class="inner third">3</div>
</div>

And this CSS

.wrapper {
  width: 500px;
  height: 500px;
  margin: 100px auto;
  border: 1px solid black;
}

.inner {
  border: 1px solid black;
  box-sizing: border-box;
}

.first, .second {
  float: left;
  width: 300px;
  height: 300px;
}

.third {
  width: 200px;
  height: 200px;
  float: right;
}

The third div does not float all the way to the top right, but aligns with the second div

Example

I know that this happens but I would like a more specific explanation as to why (based on what rule)


Solution

  • Good question, I have seen some people having difficulty understanding this. As per your question, I feel you want to align '3' to the top-right in the box. Your inner is 500 * 500, and your first and second is 300*300, since it cannot fit total of 600, the second one will go below first one. Then there is a space of 200 for third one. It will take next 200 space (next to second one) and the space above is not utilized. To get desired output, what you want is shift 3 up as shown below so that the space of 200 in the top right is utilized first.

    May be this can help you:

      <div class="wrapper">
      <div class="inner third alg">3</div>
      <div class="inner first">1</div>
      <div class="inner second ">2</div>
      </div>
    

    CSS code:

    .wrapper {
      width: 500px;
      height: 500px;
      margin: 100px auto;
      border: 1px solid black;
    }
    
    .inner {
      border: 1px solid black;
      box-sizing: border-box;
    }
    
    .first, .second {
      float: left;
      width: 300px;
      height: 300px;
    }
    
    .alg{
      text-align: right;
    }
    
    .third {
      width: 200px;
      height: 200px;
      float: right;
    }
    

    enter image description here

    I hope this makes things more clear to you now. If not comment below, I can explain with some more examples.