【问题标题】:How to give height to the parent div based on the height of child content如何根据子内容的高度为父 div 赋予高度
【发布时间】:2021-12-09 22:14:19
【问题描述】:

我想根据子内容为父 div 分配高度(这里 SVG 是我的孩子,它有不同的大小数据)。我无法分配固定高度,因为数据是动态的。我尝试给出高度:自动但没有用。我想要在我的情况下是方形框的整个数据应该采用黑色或红色背景。由于我将 SVG 的属性设为 ("overflow", "visible"),因此内容是可见的,但不幸的是背景没有增加。

注意:我的问题是我无法为整个数据提供背景颜色,因为高度没有定义。如果我不为 SVG(child) 提供溢出属性,那么数据(方形框)也会被裁剪为背景的一半。

这是我的代码 sn-p。

React.useEffect(() => {
// calling legend function and passing div id to function
colorLegend("#legend");
}, [dep]);

function colorLegend(legend: string) {
// logic
select(legend)
.append("svg")
.attr("overflow","visible")
.attr("width", 150 + "px");
}

return (
<div style={{position: "absolute",right: 16,top: 10,backgroundColor: "red",borderRadius:"5px",padding: 
"10px"}}>
<label style={{ color: "#6F6F6F" }}>{name}</label>
<div id="legend" style={{backgroundColor: "black"}}></div>
</div> 
);

小提琴链接:https://jsfiddle.net/shru90/wvph9tx5/15/

【问题讨论】:

  • 在询问 HTML 和 CSS 问题时,您应该发布呈现的标记而不是 React 代码。最重要的是,这是一个古老问题的重复,但我没有时间去寻找。
  • @Rob 我同意。当我最近开始在堆栈溢出中提出问题时,我没有意识到这一点,但从下一次开始会记住。虽然它看起来像重复和陈旧,但在 SVG 方面并不那么容易。
  • @Rob 你有时间能帮我解决这个问题吗?这是小提琴链接:jsfiddle.net/shru90/wvph9tx5/15。黑色或红色背景应覆盖整个内容。还要记住不要给出固定的高度,因为 SVG 内容可能会有所不同。

标签: css svg height overflow background-color


【解决方案1】:

#initial{
  display: block;
  min-width: 100px;
  min-height: 200px;
}
#initial{
  position: absolute;
  right: 16;
  top: 10;
  background-color: red;
  border-radius: 5px;
  padding: 10px;
}
#label{
  color:#6F6F6F;
}
#legend{
  display: flex;
  min-height: 200px;
  min-width: 100px;
  background-color: black;
  color: aliceblue;
  margin:0 auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="github.css">
    <style>
    </style>
</head>
<body>
    <div id="initial">
    <label id="label">Label name</label>
<div id="legend">123242242424wewdsdsdsdssdsdsdsd</div>
</div> 
</body>
</html>

您可以使用 min 属性限制高度和宽度。在我上面插入的代码中,你可以插入任何东西,它的高度和宽度会相应地改变,但数据永远不会超过它。

【讨论】:

  • 不幸的是,您的解决方案不适用于我的情况。可能是因为它是 SVG 而不是普通的 div,但不确定。 id intial 的高度不会根据内容增加,因此内容会被裁剪。
  • 在我的代码中,我将 SVG 附加到 id “legend”,如果我给出溢出:可见,内容不会被裁剪(完全显示)但背景颜色被裁剪(父 div 初始不高度增加),因此溢出的内容不会显示背景颜色。
  • 我将尝试为我的问题创建一个小提琴链接并为您提供链接。
  • @Developer 你确实是对的。由于 SVG,似乎存在问题。我尝试了很多东西,但似乎都没有。唯一可行的方法是手动增加最小高度。但否则,高度不会自动增加。我还在 StackOverflow 上找到了相同问题的链接,但没有任何相关内容。无论如何我都会在这里发布它,也许你能找到一些东西。链接:stackoverflow.com/questions/8919076/…
  • 是的,即使我尝试了很多东西,但都没有奏效,因此最后我在 SO 中发布。不幸的是,我不能手动给出高度,因为 SVG 内容是动态的并且高度不同。感谢您的努力。
猜你喜欢
  • 2021-12-07
  • 2014-11-29
  • 2018-10-24
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 2013-03-10
  • 1970-01-01
  • 2016-09-27
相关资源
最近更新 更多