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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:01:32  来源:igfitidea点击:

CSS Stretch to Available Width

csshtmlwidth

提问by Oliver Spryn

How do I make a block-level element, such as a divstretch 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 divto 20% on each side. Setting the widthproperty 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 divstretches 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:fixedproperty 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;
}

Demo

演示

回答by winsly

Make sure body has 0padding and margin.

确保正文有0填充和边距。

Any divinside should take every bit of space available.

任何div内部都应充分利用可用空间。