表单元素忽略绝对位置

时间:2015-01-30 20:55:59

标签: html css

我正在尝试对输入元素使用绝对定位。 Gecko / Blink似乎忽略了“右”样式(应强制宽度),而是将默认宽度应用于元素。其他元素(如div或span)不会发生这种情况。

我知道我可以通过添加可以正确定位的其他容器来解决此问题,但我不必更改标记以使用CSS。据我所知,这是一个错误,但是有几个浏览器似乎默认这是一个很好的错误。

我对这个规格有什么误解?我如何在CSS中解决这个问题?

<style>
    .container {
        position: relative;
        height: 100px;
    }

    .container > * {
        background-color: #FAA;
        bottom: 5px;
        left: 5px;
        position: absolute;
        right: 250px;
        top: 5px;
    }
</style>

<!-- this works -->
<div class="container">
    <div>Foo</div>
</div>

<!-- this does not -->
<div class="container">
    <button>Foo</button>
</div>

小提琴:http://jsfiddle.net/t6o3jajr/4/

注意div和span如何使用容器调整大小,但输入和按钮不会。

3 个答案:

答案 0 :(得分:3)

我不确定为什么它在某些元素上的行为有所不同,但您可以通过将right: 250px;替换为width: calc(100% - 250px);来解决此问题。

Fiddle

答案 1 :(得分:1)

据我了解,行为符合CSS 2.1规范。

input元素是替换元素,因为它们的视觉由浏览器/系统定义,并且具有内在的维度。根据{{​​3}}: 第一条规则是[...]The used value of 'width' is determined as for inline replaced elements.[...]If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic width, then that intrinsic width is the used value of 'width'.[...] 如果我们将最后一条规则考虑为[...]If at this point the values are over-constrained[...],因为它具有正确的值[...]ignore the value for either 'left' (in case the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value.

我可能错了,但以这种方式阅读行为是正确的。

修改 我在FireFox和Chrome的问题跟踪器中进行了一些搜索,看起来我的阅读是正确的:

<强>的Bugzilla @ Mozilla的:
10.3.8 Absolutely positioned, replaced elements

<强>铬:
Bug 416634 - Inputs no longer stretched by "position:absolute; left:#; right:#" style
Issue 281380: Inputs do not follow the rules for replaced absolutely positioned elements correctly

答案 2 :(得分:0)

我尝试了你的脚本...按钮似乎工作。然而...

在css中试试......

.container {
    position: relative;
    height: 100px;
    background-color: lightblue;
}

.container > * {
    background-color: #FAA;
    bottom: 5px;
    left: 5px;
    position: absolute;
    right: 250px;
    top: 5px;

    /* This is important to give a maximum width
       to all elements inside container */
    width:100%;
    max-width:500px;
}

/* Remove border from input box to be perfectly aligned
   to other elements */

input{
    border:0;
}

...这在html中

<div class="container">
    <div>Foo</div>
</div>

<div class="container">
    <span>Foo</span>
</div>

<div class="container">
    <input value="Foo" />
</div>

<div class="container">
    <button>Foo</button>
</div>
  

输入对话框与其他元素的工作方式不同。它具有不同的最小尺寸,因此如果您未指定width,则它比其他尺寸短。   因此,请设置.container > *width:100%;max-width:500px;。   因此,您确定<div class="container">中的所有元素都具有相同的大小。对于输入框类型,我建议删除边框以与其他元素完美对齐。

     

注意:您可以根据需要为max-width选择任何px值。

Woking演示:http://jsfiddle.net/Yeti82/x0zb4njo/