Html CSS 拉伸到可用宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9642705/
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
CSS Stretch to Available Width
提问by Oliver Spryn
How do I make a block-level element, such as a div
stretch to the available width?
如何制作块级元素,例如div
拉伸到可用宽度?
I know that this may seem like a question with an obvious answer, but it is a tad bit more complicated that it seems, have a look at this Fiddle:
我知道这似乎是一个有明显答案的问题,但看起来有点复杂,看看这个 Fiddle:
http://jsfiddle.net/spryno724/pZKgv/
http://jsfiddle.net/spryno724/pZKgv/
The CSS sets a left and right margin for the containing div
to 20% on each side. Setting the width
property causes it to stretch 100% of the originalavailable space, causing it to spill off the side of the screen when the 20% margins are added to each side.
CSS 将包含的左右边距设置为div
每边 20%。设置该width
属性会导致它拉伸 100% 的原始可用空间,当每边添加 20% 的边距时,它会从屏幕的一侧溢出。
How can this be fixed, such that 20% margins still exist, but the div
stretches to fill the remaining space in between?
如何解决这个问题,使得 20% 的边距仍然存在,但div
拉伸以填充两者之间的剩余空间?
回答by c_maker
This is what you had:
这就是你所拥有的:
.error {
border: 1px solid black;
display: inline-block;
margin-left: 20%;
margin-right: 20%;
position: fixed;
top: 0;
width: 100%;
}?
Try this one:
试试这个:
.error {
border: 1px solid black;
margin-left: 20%;
margin-right: 20%;
top: 0;
}?
回答by Andres Ilich
the cleanest way i see you going about this aside from the mentioned fix (setting the width to 60%) is to enclose that error div inside a container and add the position:fixed
property to that. That way you can style your error message and not have to worry about style issues that might arise from positioning the element itself (like a bleeding background color, padding, or overflow issues).
除了提到的修复(将宽度设置为 60%)之外,我看到你解决这个问题的最干净的方法是将该错误 div 包含在一个容器中并将position:fixed
属性添加到该容器中。这样,您可以设置错误消息的样式,而不必担心因定位元素本身而可能出现的样式问题(如背景颜色、填充或溢出问题)。
HTML
HTML
<div class="fixed">
<div class="error">Error!!!</div>
</div>
CSS
CSS
.error {
border: 1px solid black;
margin-left: 20%;
margin-right: 20%;
}
.fixed {
position: fixed;
top: 0;
left:0;
right:0;
}
回答by winsly
Make sure body has 0
padding and margin.
确保正文有0
填充和边距。
Any div
inside should take every bit of space available.
任何div
内部都应充分利用可用空间。