如何根据内容调整div的高度

CashbyCoder

我设计了一个可重用的ListItem组件,然后将其映射到另一个组件中以创建一个List。该列表在扩展的窗口中看起来不错,但是当我缩小窗口大小时,文本溢出div并溢出到列表中的后续项上。我正在尝试了解如何制作它,以便列表项的高度根据里面的文本而变化。

我一直在寻找答案,并尝试了以下失败的尝试:

  1. 在#list-item中设置高度:自动
  2. 在#list-item中设置height:fit-content
  3. 在显示组件中,在映射过程中将“ display:block”样式应用于ListItem组件。

问题截图

上面的解决方案1和2的结果

使用解决方案3没什么区别

ListItem.js

export default function ListItem(props) {

  const [anchorEl, setAnchorEl] = useState(null);
  const handleClick = (event) => setAnchorEl(event.currentTarget);
  const handleClose = () => setAnchorEl(null);

  return (
    <div>
      <div id='list-item'>
        <div id="label-container">
          <Typography id="type" variant="caption">{props.type}</Typography>
          <p id="title">{props.title}</p>
        </div>
          <SvgIcon id="icon" onClick={handleClick}>
            <ListIcon />
          </SvgIcon>
      </div>
      <Divider id="divider" />

      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose}>View / Edit</MenuItem>
        <MenuItem onClick={handleClose}>Add to Community</MenuItem>
        <MenuItem onClick={handleClose}>Share with...</MenuItem>
      </Menu>
    
    </div>
  )
}

ListItem.css

#list-item {
  display:flex;
  width:70%;
  min-height:54px;
  align-items: center;
  justify-content: center;
  position: relative;
  margin: 0 auto;
}

#label-container {
  display:flex;
  flex-direction: column;
  justify-content: center;
}

#type {
  position: absolute;
  margin-right: 40px;
  top: 5px;
  left: 10px;
}

#title {
  position: absolute;
  margin-top: 0px;
  margin-right: 40px;
  top:25px;
  left:10px;
}

#divider {
  width:70%;
  margin: 0 auto;
}

#no-margin {
  margin:0;
}

#icon {
  position: absolute;
  fill: #70CDE5;
  right: 10px;
}

@media screen and (max-width: 600px){
  #list-item{
    width:100%;
  }

  #divider {
    width: 100%;
  }
}

显示组件

...

{listData.map((item, index) => (
   <ListItem key={item.title} type={item.type} title={item.title} />
))}

...

谢谢

达尼特拉胡

这可能是因为你有position: absolute你的Typographyp

设置position: absolute为任何元素时,它将其从文档流中删除,这就是为什么列表高度是min-height: 54px唯一的原因。

尝试移除 position: absolute

#type {
  margin-right: 40px;
}

#title {
  margin-top: 0px;
  margin-right: 40px;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章