Chris
Chris

Reputation: 21

HTML/CSS Float top and left

I have a page design that requires a somewhat unique layout. I have a couple of div elements of various sizes. The below code is a simplified example of the page.

<div style="width:500px;">
  <div style="height:300px; width:100px; background-color:blue; float:left;"> </div>
  <div style="height:100px; width:300px; background-color:green; float:left;"> </div>
  <div style="height:300px; width:100px; background-color:yellow; float:left;"> </div>
  <div style="height:100px; width:100px; background-color:black; float:left;"> </div>
  <div style="height:100px; width:100px; background-color:purple; float:left;"> </div>
</div>

Can I force the black and purple div elements to appear directly below the long green div and left of the tall blue div? Since they cannot fit on the top row, they automatically move below previous element, so they end up at the bottom. I need them to fill in the space below the long green div and left of the tall blue div.

Upvotes: 2

Views: 2861

Answers (2)

Paulie_D
Paulie_D

Reputation: 115045

If the elements are fixed sizes (multiples of 100px say), this is possible with CSS-Grid but otherwise....you will need javascript.

.grid {
  display: grid;
  margin: 1em auto;
  grid-template-columns: repeat(5, 100px);
  grid-template-rows: repeat(6, 100px);
}

.two {
  grid-column: 2/5;
}

.four {
  grid-column: 2;
}
<div class="grid" style="width:500px;">
  <div class="one" style="height:300px; width:100px; background-color:blue;"> </div>
  <div class="two" style="height:100px; width:300px; background-color:green;"> </div>
  <div class="three" style="height:300px; width:100px; background-color:yellow;"> </div>
  <div class="four" style="height:100px; width:100px; background-color:black;"> </div>
  <div class="five" style="height:100px; width:100px; background-color:purple;"> </div>
</div>

Upvotes: 0

Torjescu Sergiu
Torjescu Sergiu

Reputation: 1533

Yes if you change your html logic like this:

<div style="width:500px;">
<div style="height:300px; width:100px; background-color:blue; float:left;"> </div>
<div style="float: left; display: inline-block;">
    <div style="height:100px; width:300px; background-color:green;"></div>
    <div style="height:100px; width:100px; background-color:black; float: left;"> </div>
    <div style="height:100px; width:100px; background-color:purple; float:left;"> </div>
</div>
<div style="height:300px; width:100px; background-color:yellow; float:left;"> </div>
</div>

Upvotes: 1

Related Questions