首页 > 解决方案 > 尽管有内容,但反应 div 标签高度为零,

问题描述

在我的项目中,我有一个Pokedex 类标签,其中包含一些 Pokecard 组件(在图片上可见),但是,div 标签的高度始终为零,只有在我在 CSS 中将其设置为 fe height=1000px; 高度设置正确。例如查看屏幕 问题说明

我的代码:CSS:

.Pokecard img {
  margin-left: auto;
  margin-right: auto;
  display: block;
}

.Pokecard p {
  text-align: center;
  margin: 3px;
}

.Pokecard {
  border: 1px solid black;
  width: 20%;
  max-width: 180px;
  min-width: 100px;
  border-radius: 10px;
  padding: 10px;
  background-color: rgb(235, 199, 238);
  float: left;
  margin: 2%;
}


.Pokedex {
  margin: auto;
  max-width: 700px;
  width: 95%;
  background-color: cornsilk;
  height: max-content;
}

图鉴组件:

  myProps = this.props.prokeList;
  render() {
    return (
      <div className="Pokedex">
        {[...this.myProps].map((e, index) => {
          return (
            <Pokecard
              key={`pk_${index}`}
              name={e.name}
              id={e.id}
              baseExperience={e.base_experience}
              type={e.type}
            />
          );
        })}
      </div>
    );
  }
}

扑克牌组件

class Pokecard extends React.Component {
    render() {
        return (
            <div className="Pokecard">
                <h3>{this.props.name}</h3>
                <img 
                src={'https://raw.githubusercontent.com/PokeAPI/sprites/master/' +
                `sprites/pokemon/${this.props.id}.png`} alt={this.props.name}/>
                <p>Type: {this.props.type}</p>
                <p>EXP: {this.props.baseExperience}</p>
            </div>
        )
    }    
}

为什么会发生这种情况,我在浏览器检查器中看到 div.Pokedex 包含组件但高度为 0px?

已解决参考 Danko 的回答,我将这个clearfix 添加到我的 CSS 中:

.Pokedex::after {
  content: "";
  clear: both;
  display: table;
}

标签: htmlcssreactjsgoogle-chrome-devtools

解决方案


您的父元素已折叠,因为子元素是浮动的。使用清除修复。


推荐阅读