【问题标题】:Set input text box font size equal to input text box height设置输入文本框字体大小等于输入文本框高度
【发布时间】:2012-10-11 01:35:03
【问题描述】:

好的,我基本上有一个 .search_bar_container 类,如下所示:

#search_bar_container{
    width: 81%;
    overflow: hidden;
    z-index: 1;
    position: absolute;
    top: 45%;
    left: 13.3%;
    height: 10%;
}

还有一个.search_bar 类:

#search_bar{
    width: 80%;
    height: 99%;
    font-family: cursive;
    font-size: vh;
    box-shadow: 1px 1px 5px black;
}

接下来我的 HTML 看起来像这样

<div id='search_bar_container'><input id='search_bar'/></div>

问题
我的问题是如何将搜索栏的字体大小设置为等于 search_bar 的高度?到目前为止我尝试过的事情: 100%...嗯,我不知道为什么这对于设置相对于文本框的字体大小不起作用。 100vh...将大小设置为主体的 100%...我可以更改视口并将其设置为 search_bar 容器...?

【问题讨论】:

  • 对于那些不支持 vh/vw 单位的浏览器(包括,似乎,Chromium 18/Ubuntu 11.04...sigh)将使用 JavaScript回退是可以接受的,还是必须是纯 CSS(因此在不支持的浏览器中不完美)。
  • Javascript 没问题。你有什么推荐的?
  • 还不确定;我对 Chromium 的失败感到惊讶,并研究如何切换到 beta/unstable nightly/dev 分支。所以,嗯,还没有真正研究它。我假设您希望字体大小为视口高度的 9.9%(ish)?
  • 我只希望字体大小等于文本框高度的 95%。实际上我不在乎网页是否放大。我只是希望能够在加载时设置字体大小。

标签: html css font-size


【解决方案1】:

我知道已经晚了,但我想与您分享我的解决方案。当页面加载和调整页面大小时,我使用 JavaScript 更改输入字体。将font-size 设置为输入的offsetHeight。然后字体大小将等于输入高度。我认为文字不适合,这就是为什么我使用 70% 的高度这样:

//when window changes its size, make text fit again
window.onresize = function(event) {
    document.getElementById("username").style.fontSize = (document.getElementById("username").offsetHeight*0.7) + "px";
    document.getElementById("password").style.fontSize = (document.getElementById("password").offsetHeight*0.7) + "px";
};

//when page loads make text fit text box
function myFunction(){
document.getElementById("username").style.fontSize = (document.getElementById("username").offsetHeight*0.7) + "px";
document.getElementById("password").style.fontSize = (document.getElementById("password").offsetHeight*0.7) + "px";
}
#username{
width:85%;
height:100px;
font-size:25px;
padding-left:20px;
padding-right:20px;
}

#password{
width:85%;
height:50px;
font-size:25px;
padding-left:20px;
padding-right:20px;
}

body{
text-align:center;
}
<html>
<body onload="myFunction()">
<p><input type="text" id="username" placeholder="Username"/></p>
<p><input type="password" id="password" placeholder="Password"/></p>
</body>
</html>

如果您想将字体大小设置为大于或小于输入高度的 70%,请将 0.7 更改为您想要的数字。

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 2020-03-21
    • 1970-01-01
    • 2016-06-15
    • 2012-01-13
    • 2019-01-06
    • 1970-01-01
    • 2017-03-24
    • 2015-09-08
    相关资源
    最近更新 更多