HTML & CSS
If i want to space elements from each other - i am not sure when to use what in every situation. An example:
I want to add some space between these elements.
padding-top: 40px; ???
I'd go with a margin for this case but there's no hard and fast rules about it.
The differences are that margins are never visible and that they can collapse into each other.
Padding sits inside the background and borders so is a visible part of the element.
I'd say margins there, which is really for pushing elements apart. But I'd also advise against having inline elements butting up against block elements. I find it's a recipe for layout problems, even if the image is set to display: block.
i am not sure when to use what in every situation
That's because there is not a simple answer I'm afraid The answer varies depending on the situation
Vertical margins will collapse between certain elements so their effect will be dependent on what went before and what follows after and what type of element it is and what properties it has been assigned.
If you use a top margin on an element that clears a float then it will appear to have no effect because the top margin will already be automatically changed so that it clears the float as margins of static elements stretch under the float and reach the top of the original containing block as though the float was not there. In this case padding top on the cleared element would provide you with the extra space required or indeed applying a bottom margin to the float above.
Vertical margins of certain elements do not collapse however so if you are using floats or inline-block elements then their margins are fully applied without collapsing
Inline elements do not apply vertical margins so they are no use and although vertical padding has an effect on the inline element it will not affect the line-height of the element and thus not change the flow and will just spread out over what is in the way.
As a general rule for static elements using margin is the preferred method to make space but you do need to take into account margin-collapse, although in most cases that is what you want.
This topic is now closed. New replies are no longer allowed.