我正在使用flexbox布局,并尝试在特定div中获取文本以进行调整以适合该div。
例如,如果我有如下代码:
<div style={{display: "flex"}}>
<div style={{flex: 1}}>
A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
</div>
<div style={{flex: 1}}>
Some other text
</div>
</div>
实际上,文本将从数据库中提取,因此长度是动态的。
如何在第一个div中获取文本以自动调整以适合整个div?
说明: div应该保持固定大小,并且只有文本应该缩小以适合div,而不是使div溢出。
更新
答案 0 :(得分:2)
您只需将尺寸硬编码为50%
<div style="display:flex">
<div style="width:50%;background:lightgrey;">
A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
</div>
<div style="width:50%;background:lightblue;">
Some other text
</div>
</div>
答案 1 :(得分:0)
我不是reactJs用户,但是我使用过CSS flex
您可以将容器的高度设置为自动,以便随着我们得到内容而改变容器的高度。另外,您应该在CSS中设置min-height和max-height
属性,以便如果内容小于给定长度,则它会显示在min-height
上,如果内容变大,则不会超过给定长度容器高度。
为了禁止内容开箱即用,您可以使用overflow:hidden
。这样可以避免内容开箱即用。
希望这对您的操作方式有所帮助。
答案 2 :(得分:0)
pkill -u username
答案 3 :(得分:0)
这里有一些代码可以满足您的要求。
let size_div = document.querySelector("#font_size");
let div = document.querySelector("#fixed");
while (div.scrollHeight > div.clientHeight) {
let style = window.getComputedStyle(div, null).getPropertyValue('font-size');
let fontSize = parseFloat(style);
if (fontSize <= 1) {
break;
}
div.style.fontSize = "" + (fontSize - 1) + "px";
size_div.innerHTML = " " + div.style.fontSize;
}
您可以在这里尝试: https://codepen.io/lowtex/pen/xNawEO
答案 4 :(得分:0)
您尝试的方法是正确的,请看下面的示例,我只是使用类而不是内联样式:
function addText() {
document.querySelector('.child').innerHTML += " A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.";
}
function reset() {
document.querySelector('.child').innerHTML = "A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.";
}
.parent {
display: flex;
}
.child {
flex: 1;
}
<button onclick="addText()">Add text</button>
<button onclick="reset()">Reset</button><br /><br />
<div class="parent">
<div class="child">
A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
</div>
<div class="child">
Some other text
</div>
</div>