The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> Html, Difference between margin and padding
deb1
post Dec 4 2022, 11:11 PM
Post #1


Advanced Member
****

Group: Members
Posts: 109
Joined: 7-May 20
Member No.: 27,330



Can someone please explain to me what is
the difference between padding and margin
in html?
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Dec 5 2022, 07:43 AM
Post #2


.
********

Group: WDG Moderators
Posts: 9,630
Joined: 10-August 06
Member No.: 7



In CSS padding is the spacing closest to the element, surrounded by a possible border and then with margin on the outside. There are also some special cases where margin behaves different than padding, such as collapsing adjacent margins or when using "box-sizing: border-box".

HTML used to have some similar attributes, such as CELLPADDING and CELLSPACING for tables, or VSPACE and HSPACE for image margins, but these are deprecated nowadays.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Jason Knight
post Dec 25 2022, 06:55 AM
Post #3


Advanced Member
****

Group: Members
Posts: 100
Joined: 25-December 22
Member No.: 28,719



Easiest way to think about it is to say the border exists, even if it's width is zero.

Padding goes inside the border around the content.

Margin goes outside the border, and in most cases can overlap the border of other elements. This overlap and escaping the parent is called "margin collapse"

A simple demo can be used to show this. Let's make an outer div set to overflow:hidden; A side effect of that overflow state is that margins are "contained" and do not pass outside their parent (overriding margin collapse)

If we set inside that containing DIV two paragraphs set to margin:1rem 1rem 2rem; with 2rem padding and a 0.5rem back border, colouring the backgrounds...

Well, here's a pen:

https://codepen.io/jason-knight/pen/poZjwoj

In the first section see how the padding pushes the text away from the green border, but the blue of the parent is showing? See how while both have 2em of bottom margin and 1em of top, the space between them is only 2em, the larger of the two values?

In the second set of examples see how the first one with no margin or padding sits flush, but the second one's margin escapes top and bottom pushing it away from its sibling?

That in a nutshell is margin collapse.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 29th March 2024 - 04:52 AM