Search code examples
htmlcssfloating

Using floats, how can I get the purple <div> box to line up exactly below the yellow box and to the right of the blue box?


Using floats, how can I get the purple box to line up exactly below the yellow box and to the right of the blue box? If I use clear left on the purple box it will line up right below the blue box, so that is not a solution. Can see the image on the link below. Thanks!

<!DOCTYPE html>

<html class="no-js" lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Float Demo</title>

    <style>

        body {
          background-color: #FFFFFF;
        }

        li {
          display: inline-block;
        }

        #box {

          width: 200px;
          border-style: solid;
          border-width: 1px;
          border-color: Black;
        }

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

        .green {
          background-color: green;
          float: left;
          height: 200px;
        }

        .blue {
          background-color: blue;  
          height: 400px;
          float: left;
          clear: left;
        }

        .yellow {
          background-color: yellow;
          float: left;
          height: 200px;
        }

        .purple {
          background-color: purple;
          float: left;
          height: 200px;
        }

        </style>
  </head>
  <body>

    <div id="box" class=red></div>
    <div id="box" class=green></div>
        <div id="box" class="blue"></div>
    <div id="box" class=yellow></div>
        <div id="box" class=purple></div>


  </body>
</html>

Click this line to link to the file I'm having trouble with


Solution

  • Wrap the yellow and purple boxes in their own div. Also, use a class for the boxes instead of multiple ids - having multiple elements share the same id is bad form.

    <!DOCTYPE html>
    <html>
    <head>
    <style>
        .lv-1 { float: left; }
    
        .box {
            width: 200px;
            height: 200px;
            border: 1px solid black;
        }
    
        #red { background-color: red; }
        #green { background-color: green; }
        #blue {
            background-color: blue;
            height: 400px;
            clear: left;
        }
        #yellow { background-color: yellow; }
        #purple { background-color: purple; }
    </style>
    </head>
    <body>
        <div id='red' class='box lv-1'></div>
        <div id='green' class='box lv-1'></div>
        <div id='blue' class='box lv-1'></div>
        <div class='wrap lv-1'>
            <div id='yellow' class='box'></div>
            <div id='purple' class='box'></div>
        </div>
    </body>
    </html>
    

    jsfiddle: https://jsfiddle.net/jpqq99h9/