【问题标题】:How to adjust height of div based on content如何根据内容调整div的高度
【发布时间】:2020-10-06 17:07:31
【问题描述】:

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

我已经搜索了答案并尝试了以下方法但没有成功:

  1. 在#list-item 中设置高度:自动
  2. 在#list-item 中设置高度:适合内容
  3. 在显示组件中,在映射期间将“display:block”样式应用于 ListItem 组件。

Issue Screenshot

Result of solutions 1 and 2 above

使用解决方案 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} />
))}

...

谢谢

【问题讨论】:

    标签: css reactjs


    【解决方案1】:

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

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

    尝试删除position: absolute

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      相关资源
      最近更新 更多