Padding on floating elements [closed]

六月ゝ 毕业季﹏ 提交于 2019-12-21 20:32:48

问题


How do I add padding to a float:right item without having it to mess up everything? Isn't padding supposed to work on the inside not the outside? Look at what happens with some padding on the green part: http://lauradifazio.altervista.org/cms/


回答1:


The total space your element (any element, floated or not) takes up is as follows:

totalWidth = contentWidth + margin + border + padding

When you specify a width property with CSS, you're only setting the contentWidth of the above equation.

For example, if you were trying to fit an element into a given amount of space, you need to take all of the width factors into consideration, not just one. So, if you only have 200px of space, and you want a 5px margin around the content, with a 1px border, and 10px of padding, you would have to work it as follows:

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.

So in your CSS, you would style the element as:

width: 168px;
border: 1px <color> <type>;
padding: 10px;
margin: 5px;

This is how the W3C (i.e. the standard) box model works. There are other box models you can force, using the box-sizing CSS property to define how you want your box model to work, but you should use the standard box model where possible.




回答2:


Remember that padding is added on to your width. So your 200px width is actually 210px if you include the 5px padding. The correct width should be 190px.




回答3:


The width of an element does not include padding. If you add padding to an element, you must decrease width and height accordingly.




回答4:


You need to compensate for the width of the element. In your case, make the div's width 190px instead of 200px since you have 5px of padding.

Helpful Resource: http://www.yourhtmlsource.com/stylesheets/cssspacing.html



来源:https://stackoverflow.com/questions/4208939/padding-on-floating-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!