简体   繁体   English

CSS:100%宽度和边距

[英]CSS: 100% width and margin

Please see example at 请参阅示例

http://jsfiddle.net/cne94hw4/ http://jsfiddle.net/cne94hw4/

.a{
      width: 100%;
    background-color: #eee;
    margin-left: 200px;
}

I was expecting "width 100%" will mean 100% of the windows, but clearly it's not when I add a margin to it. 我原本以为“宽度100%”将表示100%的窗口,但是显然不是在向其添加边距时。 I found this is difficult to understand. 我发现这很难理解。

What's the exact relationship of the box and the margin? 盒子和边距的确切关系是什么? It's there any written rule for this? 是否有任何书面规定?

Your question is about the CSS Box model, which is described in detail at the CSS specification: http://www.w3.org/TR/CSS2/box.html 您的问题是关于CSS Box模型的,在CSS规范中对此有详细说明: http : //www.w3.org/TR/CSS2/box.html

In brief, the width defines the width of the content box. 简而言之, width定义了内容框的宽度。 If you add padding, borders and margins, then the overall width of the block box is the width of the content box plus any widths due to padding, borders and margins. 如果添加了填充,边框和边距,则块框的总宽度是内容框的宽度加上由于填充,边框和边距而引起的任何宽度。

As for the height , padding and border widths are added to the overall heigth of the block. 至于height ,则将填充和边框宽度添加到块的整个高度。 Margins, though, can collapse with the margins of adjacent blocks, which is another topic to look at (see: collapsing margins ). 但是,页边距可能会随着相邻块的页边距一起折叠,这是另一个要研究的主题(请参阅: 折叠边距 )。

Another concept is the block formatting context , which comes into play if you deal with elements that may be floated or positioned. 另一个概念是块格式化上下文 ,如果您处理可能浮动或定位的元素,它将发挥作用。

In your example, the overall width of the a element is 100% plus 200px due to the left margin. 在您的示例中,由于左边距, a元素的整体宽度为100%加200px。

Finally, you can have some control over how the width is computed by using the box-sizing property. 最后,您可以使用box-sizing属性来控制宽度的计算方式。

width: 100%' does mean 100%` of the document your example, but you also set a margin, which is what's limiting the width of the element. width: 100%' does mean您的示例文档的100%`,但是您还设置了一个边距,这限制了元素的宽度。 See what happens when you remove it. 查看将其删除时会发生什么。

try the following 尝试以下

.class{  
   width:100%;
   padding-left:200px;
   box-sizing:border-box;
}

margin adds extra space out of the box. 页边空白增加了开箱即用的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM