What exactly is the difference between margin and padding in CSS? It really doesn't seem to serve much purpose. Could you give me an example of where the differences lie (and why it is important to know the difference)?
相关问题
- Adding a timeout to a render function in ReactJS
-
Why does the box-shadow property not apply to a
- Add animation to jQuery function Interval
- jQuery hover to slide?
- Issue with star rating css
Margin and padding are both types of padding really....One (margin) goes outside of the elements border to distance it from other elements and the other (padding) goes outside of the elements content to distance the content from the elements border.
Padding allows the developer to maintain space between the text and it's enclosing element. Margin is the space that the element maintains with another element of the parent DOM.
See example:
Remember these 3 points:
Demo Image:(where red box is desire control)
The simplest defenition is ; padding is a space given inside the border of the container element and margin is given outside. For a element which is not a container, padding may not make much sense, but margin defenitly will help to arrange it.
One key thing that is missing in the answers here:
Top/Bottom margins are collapsible.
So if you have a 20px margin at the bottom of an element and a 30px margin at the top of the next element, the margin between the two elements will be 30px rather than 50px. This does not apply to left/right margin or padding.
Try putting a background color on a block div with width and height. You'll see that padding increases the size of the element, whereas margin just moves it within the flow of the document.
Margin is specifically for shifting the element around.