添加内容时,将空div的高度设置为静态

时间:2022-09-25 18:00:56

Our form has a height problem with a div used for text feedback.

我们的表单存在高度问题,div用于文本反馈。

On a webpage I have a empty div with an id that has a style applied to it. Javascript is applied to the div when a user enters information into a form. Before the Javascript runs and put text into the div it has only a few pixels in height, when the Javascript adds text the div gains height and pushes the form elements under it down. The form should remain static without moving on user interaction.

在一个网页上,我有一个空div,其id带有一个应用了它的样式。当用户在表单中输入信息时,Javascript将应用于div。在Javascript运行并将文本放入div之前,它只有几个像素的高度,当Javascript添加文本时,div获得高度并按下它下面的表单元素。表单应保持静态,而不会移动用户交互。

With text the div is 29px high. Now I can apply the following style to the div.

对于文本,div高29px。现在我可以将以下样式应用于div。

height: 29px;

This solution does not seem to be safe as other browsers might render differently or someone might be using a different font size.

此解决方案似乎不安全,因为其他浏览器可能呈现不同的方式,或者有人可能使用不同的字体大小。

What is the best practice solution to setting the height of an empty div to stop it changing size when text is added?

设置空div的高度以在添加文本时停止更改大小的最佳实践解决方案是什么?

1 个解决方案

#1


0  

If you set some fixed height (say... 29px) to the div it won't change size... To better support different font-size, and/or number of lines, you can calculate that special number (29px) as the product of your font-size * line-height * numberOfLinesYouWantToAllow, and set this number as the div's height accordingly.

如果你设置一个固定的高度(比如... 29px)到div,它将不会改变大小......为了更好地支持不同的字体大小和/或行数,你可以计算出特殊数字(29px)为font-size * line-height * numberOfLinesYouWantToAllow的乘积,并相应地将此数字设置为div的高度。

CSS

height: 29px;
overflow: auto;

#1


0  

If you set some fixed height (say... 29px) to the div it won't change size... To better support different font-size, and/or number of lines, you can calculate that special number (29px) as the product of your font-size * line-height * numberOfLinesYouWantToAllow, and set this number as the div's height accordingly.

如果你设置一个固定的高度(比如... 29px)到div,它将不会改变大小......为了更好地支持不同的字体大小和/或行数,你可以计算出特殊数字(29px)为font-size * line-height * numberOfLinesYouWantToAllow的乘积,并相应地将此数字设置为div的高度。

CSS

height: 29px;
overflow: auto;