html - 输入尺寸与宽度

标签 html css

<input name="txtId" type="text" size="20" />

<input name="txtId" type="text" style="width: 150px;" />

哪一个是最佳的跨浏览器代码?

当然这取决于要求,但我很想知道人们是如何决定的以及基于什么决定。

最佳答案

你可以同时使用。 css 样式将覆盖支持 CSS 的浏览器中的 size 属性并使字段具有正确的宽度,对于不支持的浏览器,它将回退到指定的字符数。

编辑:我应该提到 size 属性不是精确的大小调整方法:according to the HTML specification,它应该指输入将能够一次显示的当前字体的字符数。

但是,除非指定的字体是固定宽度/等宽字体,否则保证指定数量的字符实际上是可见的;在大多数字体中,不同的字符会有不同的宽度。 This question 对这个问题有一些很好的答案。

下面的片段演示了这两种方法。

@font-face {
    font-family: 'Diplomata';
    font-style: normal;
    font-weight: 400;
    src: local('Diplomata'), local('Diplomata-Regular'), url(https://fonts.gstatic.com/s/diplomata/v8/8UgOK_RUxkBbV-q561I6kFtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
@font-face {
    font-family: 'Open Sans Condensed';
    font-style: normal;
    font-weight: 300;
    src: local('Open Sans Condensed Light'), local('OpenSansCondensed-Light'), url(https://fonts.gstatic.com/s/opensanscondensed/v11/gk5FxslNkTTHtojXrkp-xBEur64QvLD-0IbiAdTUNXE.woff2) format('woff2');
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
p {
  margin: 0 0 10px 0;
}
input {
  font-size: 20px;
}
.narrow-font {
  font-family: 'Open Sans Condensed', sans-serif;
}
.wide-font {
  font-family: 'Diplomata', cursive;
}
.set-width {
  width: 220px;
}
<p>
  <input type="text" size="10" class="narrow-font" value="0123456789" />
</p>
<p>
  <input type="text" size="10" class="wide-font" value="0123456789" />
</p>
<p>
  <input type="text" size="10" class="narrow-font set-width" value="0123456789" />
</p>
<p>
  <input type="text" size="10" class="wide-font set-width" value="0123456789" />
</p>

关于html - 输入尺寸与宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1480588/

相关文章:

jquery - Wordpress 自定义弹出窗口

css - 如何选择父元素的第一个和最后一个子元素?

css - 使用 React 映射图像数组时如何创建图像背景渐变

css - 使用 CSS 设计 Sencha Touch 表单的样式 - 如何查找元素?

javascript - 在网页中高效加载隐藏/分层图像

html - 具有特殊宽度的固定 css 标题

html - 用于更改内容数量的网格布局自动高度

jQuery 淡入淡出的幻灯片表现得很有趣

javascript - 如何使用 JavaScript/CSS 制作一个圆形的 ScrollBox?

html - 在 CSS calc 中使用元素的可变宽度