skip to Main Content

My layout is not obeying my commands.

I had trouble with a layout so I created a new basic box with sub-boxes to see what’s going on, and no matter what I do the two 300px boxes won’t fit side-by-side into the 600px box.

Also, when the 2nd 300px box is forced to a 2nd line there’s an unexplained margin between it and the box above.

I checked CSS & HTML validators and they presented no errors.

Any insight to the cause of the annoyance would be greatly appreciated.

System:
Chrome: Version 114.0.5735.106 (Official Build) (64-bit)
Linux Mint 19.3 Cinnamon v:4.4.8, Kernel: 5.4.0-150-generic
(Potential) pebkac model: 1969

<!DOCTYPE html>
<html lang="en">
<head>
<title>widthtest</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0">
<style>

html, body {
border: 0;
height: 100%;
margin: 0;
padding: 0;
box-sizing: border-box;
font: normal 16px/16px Arial;}

main {
background: #000;
height: 600px;
margin: 25px;
width: 600px;
}

#left, #right {
display: inline-block;
height: 300px;
width: 300px;
}

#left {
background: #cfc;
}

#right {
background: #ccf;
}

</style>
</head>

<body>

<main>
<div id="left">
</div>
<div id="right">
</div>
</main>

</body>
</html>

2

Answers


  1. 2 x 300px elements won’t fit into a 600px element. Try making them 295px each and you should see it work. Then you can experiment.

    enter image description here

    Login or Signup to reply.
  2. This is due to the white space. If you remove all white space between the divs, you’ll get your intended pixel-perfect result.

    html, body {
    border: 0;
    height: 100%;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font: normal 16px/16px Arial;}
    
    main {
    background: #000;
    height: 600px;
    margin: 25px;
    width: 600px;
    }
    
    #left, #right {
    display: inline-block;
    height: 300px;
    width: 300px;
    }
    
    #left {
    background: #cfc;
    }
    
    #right {
    background: #ccf;
    }
    <main>
    <div id="left">
    
    </div><div id="right">
    
    </div>
    </main>

    However, I think a better way to go about this is to use Flexbox.

    html, body {
    border: 0;
    height: 100%;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font: normal 16px/16px Arial;}
    
    main {
    display: flex; /* <- */
    background: #000;
    height: 600px;
    margin: 25px;
    width: 600px;
    }
    
    #left, #right {
    /* display: inline-block; */ /* <- */
    height: 300px;
    width: 300px;
    }
    
    #left {
    background: #cfc;
    }
    
    #right {
    background: #ccf;
    }
    <main>
    <div id="left">
    </div>
    <div id="right">
    </div>
    </main>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search