CSS 宽度:100% 位置:绝对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7978195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
width: 100% with position: absolute
提问by Wesley
If you do:
如果你这样做:
<div style="width: auto; background: red; color: white">test</div>
You get a div that is stretched to fill the entire screen width (100%). That is what I need to happen.
你会得到一个被拉伸以填充整个屏幕宽度 (100%) 的 div。这就是我需要发生的事情。
However, I also need the starting position to be set. So, I need position: absolute
.
但是,我还需要设置起始位置。所以,我需要position: absolute
.
When I add position:absolute, the width of the div
is only as wide as the content within (similar to floats). Is there any way around this?
当我添加 position:absolute 时,the 的宽度div
仅与其中的内容一样宽(类似于浮动)。有没有办法解决?
I cannot simply specify width: 100%
since this does not take in to account border sizes, etc.
我不能简单地指定,width: 100%
因为这没有考虑到边框大小等。
回答by thirtydot
When I add position:absolute, the width of the div is only as wide as the content within.. (Similar to floats). Is there any way around this?
I cannot simply specify width:100% since this does not take in to account border sizes, etc..
当我添加 position:absolute 时,div 的宽度只和里面的内容一样宽(类似于浮动)。有没有办法解决?
我不能简单地指定 width:100% 因为这没有考虑到边框大小等。
You could use position:absolute; left:0; right:0; top:0
.
你可以使用position:absolute; left:0; right:0; top:0
.
Like this: http://jsfiddle.net/thirtydot/yQWGV/
回答by Andreas Eriksson
You can use width:100% and the css attribute box-sizing, to get the box model working like IE 5.5, i.e. padding and border counted into the width.
您可以使用 width:100% 和 css 属性 box-sizing,使框模型像 IE 5.5 一样工作,即填充和边框计入宽度。
div.absolute {
width: 100%;
border: 5px solid #000;
background-color: #F00;
position: absolute; top: 100px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
padding: 50px;
}
Here's a fiddle: http://jsfiddle.net/dJtm2/
这是一个小提琴:http: //jsfiddle.net/dJtm2/
Be wary though, as it's a relatively new CSS3 attribute and will only work in newer browsers, and as you can see from my example requires the dreadful counter-productive measure that is vendor prefixes.
不过要小心,因为它是一个相对较新的 CSS3 属性,只能在较新的浏览器中使用,而且正如您从我的示例中看到的那样,需要可怕的适得其反的措施,即供应商前缀。
回答by sandeep
simply write like this:
简单地写成这样:
div.absolute {
border: 5px solid #000;
background-color: #F00;
position: absolute;
top: 100px;
padding: 50px;
left:0;
right:0;
}
in this padding & border
not increase the width of the element.
在这padding & border
不会增加元素的宽度。