When to use margin vs padding in CSS ?Ask a question
If you need space inside the block, between the edge of the element and the content use padding, on the other hand if you need space between the blocks use margin.
For an example if you are having two
divs and inside each
<div> you are having an image
- to separate the
- to give some space between image and the
divyou can use padding.
marginto separate the block from things outside it
paddingto move the contents away from the edges of the block.
By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.
To me, the biggest difference between
margin is that vertical margins auto-collapse, and padding doesn’t.
Consider two elements one above the other each with padding of 1em. This padding is considered to be part of the element and is always preserved.
So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element.
Thus the content of the two elements will end up being 2em apart.
Now replace that
padding with 1em
margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap.
So in this example, you will end up with the content of the first element followed by 1em of combined margin followed by the content of the second element. So the content of the two elements is only 1em apart.
This can be really useful when you know that you want to say 1em of spacing around an element, regardless of what element it is next to.
The other two big differences are that padding is included in the click region and background color/image, but not the margin.
- 3How can i use inheritance in c#
- 4How do you vertically align texts in CSS?
- 0In which scenario do I use a particular STL container ?
- 4What is "marquee" tag and how I can use it in HTML?
- 0When to use std::decay
- 1Which C++ JSON library to use
- 0Conditional css - hover - overflow
- 0CSS: The background color of modal-box is not changing and it is not scrollable
- 0CSS Grid image not filling entire container
- 1Return the DOM elements via a CSS selector
- 1How to use <marquee> element for setting a scrolling image?