CSS: Why an input width:100% doesn't expand in an absolute box?

泄露秘密 提交于 2019-12-11 09:57:19

问题


I have 2 inputs: they both have a width: 100%, and the second one is an absolute box:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">
            #box1 { position: absolute }
            #box1 { background: #666  }
            input { width: 100% }
        </style>
    </head>
    <body>
        <form>
            <input type="text">
            <div id="box1">
                <input type="text">
            </div>
        </form>
    </body>
</html>
  • On standard-compliant browsers, the width: 100% seems to have no effect on the input inside the absolutely positioned box, but it does on the input which is not inside that absolutely absolute box.
  • On IE7, both inputs take the whole width of the page.

Two questions come to mind:

  • Why does the width: 100% have no effect with standard-compliant browsers? I have to say that the way IE7 renders this feels more intuitive to me.
  • How can I get IE7 to render things like the other browsers, if I can't remove the width: 100% and can't set a width on the absolutely positioned box?

回答1:


Try using width:102%. It's a workaround, but it works almost perfect.




回答2:


The CSS 2.1 specification says that what happens in this case is not specified. And indeed, different browsers implemented this differently. You'll find more details on this (including more cases and screenshots) on: Width property inside an absolutely positioned box.




回答3:


position: absolute takes the element out of the document flow. Width automatically becomes auto when making position: relativeas far as I know.

I think you won't get around giving #box1 a fixed width (using a width property or coordinates like left: xyz; right: xyz) or the text input.

How can I get IE7 to render things like the other browsers, if I can't remove the width: 100% and can't set a width on the absolutely positioned box?

Good question. As far as I know, there is no fix for this behaviour. Setting width: auto should help.

Some theory on position: absolute on W3C here.




回答4:


When a block element (your div - #box1) is absolutely positioned, it's kinda loses its implied 100% width. Which is why the input cannot expand beyond its container (which is now of 0 width).




回答5:


This may sound odd, but what happens when you try width: 98%? In the past, I found that using 100% width never had a consistent result, but 98% did.



来源:https://stackoverflow.com/questions/2458731/css-why-an-input-width100-doesnt-expand-in-an-absolute-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!