【问题标题】:what does width: 50% mean when the container is body?当容器是主体时,宽度:50% 是什么意思?
【发布时间】:2016-12-09 04:09:29
【问题描述】:

body {
  background-color: skyblue;
}
div {
  width: 50%;
  height: 50%;
  background-color: yellow;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div>
  </div>
</body>

</html>

我了解到,百分比宽度是指与容器相比的比率。但是,当我将 50% 分配给 div 的宽度和高度时,我看不到 div。你能告诉我为什么,这里的百分比是什么意思吗?

【问题讨论】:

  • 您需要为bodyhtml 提供100% 的高度才能使其工作
  • 谢谢!那么 html 中的 height: 100% 是否意味着 html 的高度是窗口的 100% 呢?窗口的默认高度是多少?
  • "height: 100%" 表示容器元素高度的 100%。现在,由于body 默认具有“高度:自动”,这意味着它与包含的div 一样高。但是“auto”的 100% 为 0。因此 div 的高度为 0。因此body 的高度为 0。为了解决这个问题,你需要给身体一个明确的高度。
  • 知道了!谢谢!

标签: html css width css-position percentage


【解决方案1】:

position: absolute 添加到div 就可以了!

请了解position 如何作用于 DOM 元素。

body {
  background-color: skyblue;
}
div {
  width: 50%;
  height: 50%;
  background-color: yellow;
  position: absolute;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div>
  </div>
</body>

</html>

【讨论】:

    【解决方案2】:

    百分比是从父元素计算出来的,所以如果你设置height你也必须设置为父元素。

    【讨论】:

    • 谢谢!但是为什么身高这么特别呢?为什么我不需要设置宽度?
    【解决方案3】:

    body {
      background-color: skyblue;
      height : 100px;
    }
    div {
      width: 50%;
      height: 50%;
      background-color: yellow;
      position:absolute;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
    </head>
    
    <body>
      <div>
      </div>
    </body>
    
    </html>

    【讨论】:

    • 感谢您的帮助!
    【解决方案4】:

    在这种情况下,您必须将height 设置为固定工作,检查这里

    body {
      background-color: skyblue;
    }
    div {
      width: 50%;
      height: 100px;
      background-color: yellow;
    }
    <div>
     </div>

    【讨论】:

    • 谢谢!那么你能解释一下为什么高度如此特别吗?
    • 因为里面的 div 里面没有内容。在这种情况下,您可以检查宽度。
    • 你需要为 html, body.检查这个小提琴jsfiddle.net/f76gymqf
    • 它是自动的,只要内容进入 div 就会开始流动。
    • 如果我不给它指定一个特定的值,这是否意味着浏览器无法计算出body的一半高度?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2012-09-27
    • 2011-03-11
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多