浮动元素的填充问题

4
如何给float:right的元素添加padding而不会出现混乱?难道padding不应该在内部起作用而不是在外部吗?看看在绿色部分添加一些padding时会发生什么:http://lauradifazio.altervista.org/cms/
4个回答

9
你的元素(无论是浮动的还是不浮动的)占用的总空间如下所示:
totalWidth = contentWidth + margin + border + padding
当你使用CSS指定一个width属性时,你只设置了上述公式中的contentWidth。
例如,如果你想将一个元素适应给定的空间,你需要考虑所有的宽度因素,而不仅仅是一个。因此,如果你只有200像素的空间,并且你想要在内容周围有5像素的边距,1像素的边框和10像素的填充,则必须按照以下方式进行计算:
contentWidth = availableWidth - margin - border - padding 
contentWidth = 200px - (2x5px) - (2x1px) - (2x10px)
contentWidth = 200px - 10px - 2px - 20px
contentWidth = 168px

**note that the (2xNN) refers to the fact that you have to 
  consider both the impact to both the left and right side 
  of the element in the total.

所以在你的CSS中,你会将该元素样式设置为:
width: 168px;
border: 1px <color> <type>;
padding: 10px;
margin: 5px;

这是W3C(即“标准”)盒模型的工作方式。您可以使用box-sizing CSS属性强制使用其他盒子模型来定义您想要的盒子模型如何工作,但在可能的情况下应使用标准盒子模型。

2
当我们使用百分号时应该如何做? - user2137101

3
请记住,填充会添加到您的宽度中。因此,如果包括5px的填充,则您的200px宽度实际上为210px。正确的宽度应该是190px。

3

元素的宽度不包括内边距。如果您向元素添加内边距,则必须相应地减小宽度和高度。


2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接