2017-08-11 297 views
0

比方说,我有以下的HTML模板:css计算函数:如何计算文本的宽度?

<div id="container"> 
    <h2> Name </h2> <input type="text"> 
</div> 

,我想的是“输入”的宽度将等于容器的宽度 - “H2”中的文本的宽度。我该怎么做?

+1

如果h2'的'的内容是动态的,你不能直接CSS做到这一点;您可以使用[更少](http://lesscss.org)或[SASS(http://sass-lang.com/guide)CSS系统来做到这一点。 – Martin

+0

他们不是动态的 – CrazySynthax

+0

此外,如果你不想使用CSS预处理器,你可以使用JavaScript - > https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript –

回答

1

如果H2的内容是动态的,则不能直接在CSS中执行此操作;但是,您可以使用LESSSASS 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开发的未来。上船。

0

需要javascript

document.getElementById("yourDiv").clientWidth; // returns number, like 728 

document.getElementById("yourDiv").offsetWidth; 

您可以使用此得到h2container宽度。

计算和宽度与overflow-x: hidden添加到您的input

document.getElementById('input').setAttribute("style","width:500px"); 
1

包装input一个div内,给float: lefth2width: 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>

1

使用显示器和位置,输入将采取100%的宽度父:

h2{ 
    display:inline-block; 
} 
div{ 
    display:inline-block; 
    position: relative 
} 
input{ 
    position: absolute; 
    width:100%; 
} 

https://jsfiddle.net/qzar1we9/

+0

这个貌似正确的答案。 –