html - 如何获得两个宽度相加为 100% 的 DIV?

标签 html css

我有两个 DIV(Nav 和 Main)。当它们的宽度加到 100% 时,第二个总是浮在第一个下面。如果我将第一个 DIV 的宽度更改为 19%,将第二个 DIV 的宽度更改为 79%,它们会并排 float ,但右侧有 2% 的空白 strip 。

如何让 2 个 DIV 并排放置(即使在调整窗口大小后),以便它们合并以填充 100% 的页面宽度?

这是代码,它正在 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>

最佳答案

这里的问题是您正在使用 box-sizing: content-box(默认值),因此您需要小心填充,如果在某些时候使用不同浏览器大小的 px 会破坏布局,则边距计算。我们必须为所有布局属性(如填充、边距、边框等)使用适当的百分比值。

* {
    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%;
}

关于html - 如何获得两个宽度相加为 100% 的 DIV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37434899/

相关文章:

javascript - 如何使用嵌套在 HTML 中的 $( document ).ready() 调用函数

html - 如何使导航品牌居中对齐

html - 调整响应式网站大小时出现空白

javascript - Owl-carousel 使用 animate.css 插件从左向右滑动

javascript - 使用 CSS 和 JS 动态设置 div 尺寸时,如何补偿较长的加载时间?

javascript - CSS 动画不适用于 animate.css 跨度

javascript - 如何修复自动图像移动

html - 文本位于 div 元素背景后面

jquery - 突出显示当前页面的两级水平菜单

java - javascript 中 java 方法调用导致 chrome 崩溃