比方说,我有以下的HTML模板:css计算函数:如何计算文本的宽度?
<div id="container">
<h2> Name </h2> <input type="text">
</div>
,我想的是“输入”的宽度将等于容器的宽度 - “H2”中的文本的宽度。我该怎么做?
比方说,我有以下的HTML模板:css计算函数:如何计算文本的宽度?
<div id="container">
<h2> Name </h2> <input type="text">
</div>
,我想的是“输入”的宽度将等于容器的宽度 - “H2”中的文本的宽度。我该怎么做?
如果H2
的内容是动态的,则不能直接在CSS中执行此操作;但是,您可以使用LESS或SASS CSS实现系统来执行此操作。
如果H2
内容是相当静态的,则可以通过设置的H2
(和input
)的尺寸为所述容器的相对部分做到这一点:
#container {
width : 100%;
}
#container > h2, #container > input {
width :50%;
display :inline-block;
overflow :hidden;
box-sizing :border-box;
margin :0;
}
#container > h2 {
margin :2rem 0;
text-align :center;
}
#container > input {
padding :0.2rem;
}
上述(眉头)的示例将尺寸为标题文字货柜而非文字本身;您可以手动设置文本的大小或使用某种Javascript Text Scaling,其中有几种。
但你需要牢记的是不同的浏览器将设置一大堆的设置稍有不同(特别是在输入),所以你需要正常化这一切为好。
另一种解决方案是使用CSS Flexbox。哪个会做同样的事情;但会参考相应元素上的元素(input
)的大小(h2
)框尺寸不是框中的实际文字大小。
整体。使用LESS或SASS。这几乎是CSS开发的未来。上船。
需要javascript
为
document.getElementById("yourDiv").clientWidth; // returns number, like 728
或
document.getElementById("yourDiv").offsetWidth;
您可以使用此得到h2
和container
宽度。
计算和宽度与overflow-x: hidden
添加到您的input
document.getElementById('input').setAttribute("style","width:500px");
包装input
一个div
内,给float: left
到h2
和width: 100%
到input
h2 {
float:left;
margin: 0;
padding-right: 10px;
}
.fieldOccupyingRemaining {
overflow-x: hidden;
}
input {
width: 100%;
box-sizing: border-box;
}
<div id="container">
<h2> Name </h2>
<div class="fieldOccupyingRemaining">
<input type="text">
</div>
</div>
我管理只用CSS来做到这一点,但仅适用于Chrome:
#container{
display: inline;
position: relative;
}
h2,input{
display:inline;
}
input {
width: -webkit-fill-available;
position: absolute;
}
https://jsfiddle.net/t8a44sn5/2/
我知道这不是现在有效的答案,但在将来都可以。 http://caniuse.com/#search=fill-available
使用显示器和位置,输入将采取100%的宽度父:
h2{
display:inline-block;
}
div{
display:inline-block;
position: relative
}
input{
position: absolute;
width:100%;
}
这个貌似正确的答案。 –
如果h2'的'的内容是动态的,你不能直接CSS做到这一点;您可以使用[更少](http://lesscss.org)或[SASS(http://sass-lang.com/guide)CSS系统来做到这一点。 – Martin
他们不是动态的 – CrazySynthax
此外,如果你不想使用CSS预处理器,你可以使用JavaScript - > https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript –