CSS - 父元素高度设置为100%无效

5
当我尝试在子div上设置height: 100%时,高度仍然保持为0。
这是父div:

#game-content {
  margin-top: 50px;
  overflow: auto;
  height: 100%;
  width: 100%;
}
#game-wrapper {
  float: left;
  margin-left: 90px;
  position: relative;
  height: 100%;
}
<div id="game-content">
  <div id="game-wrapper">
    <div class="game">
      <img class="game-element" src="http://placehold.it/200x200" />
      <div class="game-element" id="description">
        <h4 id="game-header">Game1</h4>
        Desc
      </div>
    </div>
  </div>
</div>

游戏内容的高度也是100%(不是0)。尽管游戏包装器的高度保持为0,但宽度确实有效。我做错了什么?

高度属性不兼容百分比,请使用点或像素表示。 - Khurram Sharif
高度100%相对于父容器的高度,您还可以发布除div game-content之外的html和css吗?如果它直接位于body标记下方,则只需要html,body {height:100%} - Stickers
1
好的,游戏包装器必须定义高度,如果父容器也是百分比高度,则同样如此。 - Stickers
看看这个,可能对你有帮助 Height 100% CSS - Khurram Sharif
1
根据100%高度的依赖,如果相对于视口,则可以使用height: 100vh - Stickers
显示剩余2条评论
3个回答

3

如果要在#game-content中设置固定的高度,或者在其父元素(body)中设置固定的高度。如果在#game-content中设置了固定的高度,则#game-wrapper将具有其100%高度

请尝试:

#game-content
{
    margin-top:50px;
    overflow:auto;
    height:1000px;
    width:100%;
}

#game-wrapper
{
    float:left;
    margin-left:90px;
    position:relative;
    height:100%;
}

或者

body, html { /* both to be sized */
   height: 1000px; /* or 100% */
}

1
三年后,挽救了这一天! - Joshua Ohana

0
一个块级元素的高度是根据其内容来确定的。由于您正在将百分比高度赋给没有明确定义子内容高度(您也在像素中给出子内容高度)的父元素#game-content,因此会出现这个问题。给父元素指定一个特定的高度可以解决这个问题。
#game-content
{
    margin-top:50px;
    overflow:auto;
    height:someheight  px;
    width:100%;
}

#game-wrapper
{
    float:left;
    margin-left:90px;
    position:relative;
    height:100%;
}

0
我正在关注的是浮动元素的常见问题。一个浮动的元素不会像人们期望的那样影响其父元素。在这种情况下,仅浮动父元素(即#game-content)就可以解决问题。
#game-content
{
    float:left; /* just need this one line */ 
    margin-top:50px;
    overflow:auto;
    height:100%;
    width:100%;
}

我已经使用了我的答案并且它有效。这可能不是每个人都想要的确切解决方案,但这并不意味着它值得被投反对票。 - Ryan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接