15

似乎每个浏览器都在里面添加了一些神奇的硬编码填充<input type="text">。一些浏览器(IE、Safari、Chrome)使输入框有点高,但它们正确地顶部对齐,就好像它是一个常规的 HTML 元素一样。我可以忍受额外的高度。但有些浏览器行为不端(Firefox 和 Opera),也会尝试垂直对齐文本或在其上方添加一些额外的填充。我很惊讶现代浏览器不允许像 HTML 一样布局文本框并添加一些神奇的格式。难道我做错了什么?我错过了一些技巧吗?它们是一些可以帮助我的专有 CSS 属性吗?我简要查看了 Firefox CSS 文档,但找不到任何内容。或者,我可以使用可编辑的 HTML 而不是<input type="text">.

这是一个演示问题的片段:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

    <title>Test</title>

    <style type="text/css">

        body, input {
            font-family: sans-serif;
            font-size: 16pt;
            color: White; }

        #textbox {
            position: absolute;
            left: 20px;
            top: 20px;
            width: 100px;
            background-color: #A5C9E2;
            line-height: 16pt;
            padding: 0px;
            margin: 0px;
            border-width: 0px; }

        #box {
            position: absolute;
            left: 120px;
            top: 20px;
            width: 100px;
            background-color: #AFD66A;
            line-height: 16pt; }

    </style>

</head>
<body>

    <input type="text" id="textbox" value="Hello">

    <div id="box">Hello</div>

</body>
</html>

编辑:我在 Firefox 中尝试了一些-moz-outline-moz-box-sizing(以防万一),但它们的值都没有删除额外的填充。

4

2 回答 2

9

您可以通过更改输入的框大小来消除这种额外的填充。

-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
box-sizing: content-box;

它使现代浏览器的行为相同。您可能需要专门针对 IE。

于 2010-08-02T21:00:40.177 回答
3

I experimented by changing your line-height and font-size values to 20px and then inspecting the element with Firebug. The clientHeight and offsetHeight properties are both 24px (but since those properties include any padding set on the element I'm not sure if this is the browser expanding the element height, or adding padding).

Explicitly setting the height of the input to be the same as the line-height seems to do what you want, i.e. line-height: 16pt; height: 16pt; - but I suspect it works by clipping the element, as the vertical position of the text within the input doesn't change.

于 2009-12-04T13:23:03.567 回答