sw123456 sw123456 - 6 months ago 9
CSS Question

How to get two DIVs with widths that add to 100% next to each other?

I have two DIVs (Nav and Main). When their widths add to 100%, the second always floats underneath the first. If I change the first DIV's width to 19% and the second to 79%, they float side by side but with a 2% strip of white space to the right.

How can I get the 2 DIVs to sit side by side (even after resizing the window) so they combine to fill 100% of the page width?

Here is the code and it is being tested in Chrome:



<html>

<head>
<title>Space</title>
<style>
#header h1 {
text-align: center;
font-size: 40pt;
font-family: Century Gothic;
}
#header {
background: aqua;
}
#nav {
height: 100%;
width: 19%;
float: left;
background: lightblue;
}
#nav p {
font-size: 20pt;
font-family: Century Gothic;
color: yellow;
}
#main {
float: left;
padding-left: 20px;
background: linear-gradient(white, blue);
width: 79%;
height: 100%;
}
</style>
</head>

<body>

<div id="header">
<br>
<h1>All About Space</h1>
<br>
</div>



<div id="nav">
<p>Mercury</p>
<p>Venus</p>
<p>Earth</p>
<p>Mars</p>
<p>Saturn</p>
<p>Jupiter</p>
<p>Uranus</p>
<p>Neptune</p>
</div>



<div id="main">
<h3>This website is all about space</h3>
<img src="http://marshall.org/wp-content/themes/marshall/img/featured-space-policy.jpg" alt="" height="200px" width="400px">
<p>Clicking on the links to the right and you will learn all about the planets of the solar system</p>
<p>Maybe one day we will all be able to visit some of them!</p>
</div>

</body>

</html>




Answer

Problem here you are using box-sizing: content-box (default value) so you need careful about padding, margin calculation if px used at some point different browser size will break the layout. we have to you use proper percentage value for all layout property like padding, margin, border etc.

* {
    box-sizing: border-box;
}

#nav {
    height: 100%;
    width: 20%;
    float: left;
    background: lightblue;
}

#main {
    float: left;
    padding-left: 20px;
    background: linear-gradient(white, blue);
    width: 80%;
    height: 100%;
}