

CSS gets a bad rap for not behaving the way people expect. One of the things that throws people off the most are margins. They seem so simple, yet they have the potential to cause some really strange issues.
For people just getting into CSS, it's easily one of those things that can get you thinking "this is a stupid language that makes no sense!"
I see it everyday – both in the classroom as people try to figure out their spacing issues and in my YouTube comments sections as well.
In a way, margins are bit of a microcosm of CSS in general. CSS seems so simple with its property: value
pairs, but as you progress with it, you realize that there is a lot going on.
Margins also seem so simple. Add some margin, and you add some empty space around that element. But then suddenly they behave a little differently in one situation than another, or you add some margin-top
to a child element, and instead it's the parent that moves down.
Frustration ensues.
In this article, I hope to shed a little light on how margins work. We'll look at some of the common problems that happen, as well as simple solutions to those issues.
To go over all this, I'll be using examples from my Responsive Web Design Bootcamp over on Scrimba, which I pulled this simple layout from:

What are margins anyway?
Before we really jump into the deep-end here, I want to make sure we all know what margins actually are!
I'm going to assume that we all know that margins are part of the box model, with margin being all the way on the outside, coming after the content itself, the padding and the border.
The MDN explains them really well (emphasis mine):
The margin is the outermost layer, wrapping the content, padding and border as whitespace between this box and other elements. Its size can be controlled using margin and related properties.
In other words, it's effectively empty space that we can use to create space between one box and another in our layout.
Dealing with user-agent stylesheets
Browsers come with a surprising amount of CSS by default, which we call user-agent stylesheets. These styles are the reason that, without any CSS on our part, an <h1>
is bigger than an <h2>
, and why the <body>
has a margin on it that we tend to always remove.
These styles are important, but they also lead to one of the biggest issues that people run into with margins! Margins don't default to 0
on all of our elements, and this can cause all sorts of strange issues which we'll be exploring shortly.
Lists, blockquotes, paragraphs, and headings all have margin
on them (among other elements). While sometimes they're only a slight inconvenience, the default margin on paragraphs and headings seems to be the one which causes most issues out of the box.
By default, the left and right margins of a text element are set to 0
, but they all come with a margin-top
and margin-bottom
.
I often tell people that those top and bottom defaults are roughly the same as the font-size
of that element, since it's true for <p>
as well as <h3>
through <h6>
. For <h1>
it's actually 0.67em
and for <h2>
it's 0.83em
.
This means that space exists between the elements on our page even if we have not explicitly set a margin.
We'll come back to these defaults in a second.
Collapsing margins
Collapsing margins are where the headaches often start.
When two elements have vertical margins which touch each other, they effectively merge into one another.
It's already a strange behavior, and then add it to the fact that it's only for vertical margins (top and bottom), I get why people get confused and annoyed by them.
We can see this in action with the following example:
p { font-size: 18px; margin-bottom: 40px;}.links { margin-top: 40px;}
To help illustrate what's happening here, the .links
class is on the last paragraph (<p class="links">
) , which contains the two links inside it.
When people do something like this, they expect the margin between the middle paragraph and the links below it to be 80px (40px
+ 40px
), but in reality, it's 40px. The two margins are touching each other, so they merge into one another.

To push it even more, let's give our <p>
s' a margin-bottom
to 100px
:
p { font-size: 18px; margin-bottom: 100px;}.links { margin-top: 40px;}
Again, the two margins don't add together, they collapse into one another, so the total space here is 100px
.

This is a good thing
In cases like this, it's actually a good thing, though. If there are several elements with different margins, there is no need to add the margins together to see how large the gap between the elements is because we can rely on the fact that the larger margin always wins.
We often don't even think about it, it just works the way we expect it to work.
When it's not a good thing
That said, one instance where margin collapse causes all sorts of confusion is when the first child within an element has a margin-top
that merges with the parent's margin-top
.
Let's look at that same screenshot again:

There is a white space between the top of the viewport and the black box. That's not from the body (it's much bigger than the 8px
margin the body would have).
Care to guess where it's coming from?
It's actually coming from the <h1>
at the top of that black box.
Remember when I mentioned that the user-agent stylehsheets can do some odd things?
To help explain exactly what's happening here, let's add a much bigger margin-top
to the h1
.
.card { background: #000; color: white; width: 560px; margin: 0 auto;}h1 { font-size: 24px; margin-top: 100px;}p { font-size: 18px; margin-bottom: 100px;}.links { margin-top: 10px;}
I see people do this all the time, trying to push the title down within its parent. However, rather than working as expected, we get a giant space on top of the entire card!

This is because the margin-top
on the <h1>
merges with the margin-top
on the parent element.
There is nothing separating the top of the child and the parent in this case. So when we add margin-top
to the child, it touches the parent's margin-top
. And, as we saw above, when two margins touch one another, they merge into a single margin.
So while we are giving the margin to the child, it's being applied to the parent.
This is why people hate CSS.
Similarly, in the code above we gave all paragraphs a margin-bottom
. That margin on the p.link
elements touches the margin-bottom
of the .card
element, which means that the two merge together and the margin affects the .card
element instead of the links.

Although this isn't causing an issue for the site we are currently creating, it could cause problems if we later decided to add further elements to the page.
The problem is, we're using margin
for the wrong purpose
If I want space between the top of the .card
element and the children inside it, I shouldn't be using margin
anyway.
Beginners often get mixed up between margin
and padding
. My general rule of thumb is if you want empty space, use margin
. If you want more background, use padding
.
In this case, we want our .card
to have more background, so we shouldn't be adding a margin
to its children. Instead we should add padding
to that element itself.

In the image above, we can see the padding and the margin. The <h1>
on top still has a margin, but it's no longer merging with the .card
because the padding
has added in a buffer. This prevents the .card
's and h1
margin from touching one another.
As the padding adds sufficient space between the <p>
s and the <h1>
s, we can now remove the margins we previously added to them.

Margins don't always collapse
There are some exceptions to collapsing margins. The direct descendants of grid and flex parents do not have collapsing margins.
Cue the ?.
But there is a bit of a workaround for this as well, which brings us full circle back to those user agent-stylesheets we talked about at the start.
There is an easy way to avoid even thinking about collapsing margins
First off, there is my general rule of thumb that I talked about above:
- If you need empty space, use
margin
- If you need more background, use
padding
That will get you out of trouble most of the time. But let's add an extra rule to this that will help even more:
- Try to avoid
margin-top
except when you really need it
This rule is in a bit of conflict with the user-agent-styles, which set a margin-top
and margin-bottom
to a bunch of elements, which is one reason I often will do something like this:
h1,h2,h3,h4,h5,h6,p,ul,ol { margin: 0 0 1em 0; }
It eliminates a lot of the issues that come from collapsing margins on their own, as well as differences in your layout when some places are using flex or grid and others are not.
(Note: if you inspect the code here on freeCodeCamp, you'll see they do something similar as well!)
It's not a perfect solution, and I often do use a little margin-top
on certain subtitles or in specific situations where it's called for. But I'm doing it very intentionally instead of letting the user-agent-styles potentially get in the way in some unforeseen way.
These lessons are just a snippet of my much larger course on responsive web design. To continue this coding journey, take a look at the course.
In the course I cover an introduction to responsive web design, and dive into both flexbox and grid, all the while trying to show people how much fun CSS really is once you start to understand how it works.
Happy coding :)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Trying to help people fall in love with CSS
If you read this far, tweet to the author to show them you care.
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
ADVERTISEMENT
FAQs
How does the margin work in CSS? ›
In CSS, a margin is the space around an element's border, while padding is the space between an element's border and the element's content. Put another way, the margin property controls the space outside an element, and the padding property controls the space inside an element.
How do you understand margin and padding? ›In web development and design, the margin of an element represents the outside space of the element itself, while the padding represents the inner space surrounding the element. It's important to understand how different components, such as padding and margins, come together to separate text and graphics.
What does margin 10px 5px 15px 20px mean? ›If the margin property has four values:
margin: 10px 5px 15px 20px; top margin is 10px. right margin is 5px. bottom margin is 15px. left margin is 20px.
Define some width on your container and set margin top & bottom to some desired value and left & right values to auto so that it will always split the remaining space on the both sides equally.
What are the three values for margin CSS? ›When three values are specified, the first margin applies to the top, the second to the right and left, the third to the bottom. When four values are specified, the margins apply to the top, right, bottom, and left in that order (clockwise).
What is the difference between margin and markup? ›The main difference between profit margin and markup is that margin is equal to sales minus the cost of goods sold (COGS), while markup is a product's selling price minus its cost price. Margin is equal to sales minus the cost of goods sold (COGS). Markup is equal to a product's selling price minus its cost price.
What do you understand by margin? ›In the business world, margin is the difference between the price at which a product is sold and the costs associated with making or selling the product (or cost of goods sold). Broadly speaking, a company's margin is its ratio of profit to revenue.
Why are margins important in a layout? ›Margins allow us to define space between elements and padding allow us to define space inside an element. These differences are important to remember when laying out a design, as negative space will affect the composition of a design as well as where users focus throughout a page.
What is the difference between border and margin in CSS? ›Border - A border that goes around the padding and content. Margin - Clears an area outside the border. The margin is transparent.
What does padding 20px 20px mean? ›padding:20px means you give 20px padding from top right bottom left.
What does margin 30px auto mean? ›
margin: 0 auto 30px. This means margin-top is set to 0px, margin-left and margin-right are set to auto, and the bottom is 30px.
How do you set all 4 margins in CSS? ›The syntax for the CSS margin property (with 1 value) is: margin: all; When one single value is provided, the margin value will apply to all four sides of the element (ie: top, right, bottom, left).
What is the ideal padding for CSS? ›For mobile devices, the ideal padding is somewhere between 13 - 15 pixels. For tablets, padding looks best around 20 - 24 pixels. For desktop, padding is best starting at 24 pixels and progressively wider for larger screens.
Why isn t margin-right working in CSS? ›You cannot see the effect of margin-right because the 'width' property of div causes the margin of div to have more than 10px distance from the right wall of the body. Consequently, it causes the margin-right property not to have any visual effect.
How do you calculate margin and padding in CSS? ›Any margin or padding that has been specified as a percentage is calculated based on the width of the containing element. This means that padding of 5% will be equal to 5px when the parent element is 100px wide and it will be equal to 50px when the parent element is 1000px wide.
What is the important rule in CSS and why should you generally avoid it? ›The !important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!
What is the difference between margin auto and margin 0 auto? ›if you write only 0 you set all margins to 0 independent of window/Browser size. margin auto means: center the block margin 0 means set the margin to 0 but you have to set the display attribute to "block", without this your tags are floating.
What is the difference between margin and margin-top in CSS? ›"Margin is that space between the edge of an element's box and the edge of the complete box, such as the margin of a letter. 'top' displaces the element's margin edge from the containing blocks box, such as that same piece of paper inside a cardboard box, but it is not up against the edge of the container."
What is a good margin? ›You may be asking yourself, “what is a good profit margin?” A good margin will vary considerably by industry, but as a general rule of thumb, a 10% net profit margin is considered average, a 20% margin is considered high (or “good”), and a 5% margin is low.
What is 30% margin to markup? ›To arrive at a 30% margin, the markup percentage is 42.9%
Is 100% markup the same as 50% margin? ›
If the cost of an offer is $1 and you sell it for $2, your markup is 100%, but your Profit Margin is only 50%. Margins can never be more than 100 percent, but markups can be 200 percent, 500 percent, or 10,000 percent, depending on the price and the total cost of the offer.
How do you read a margin statement? ›It shows if you have used all your available margin or if you need to deposit more funds to avoid a penalty. If the number is positive, then you have funds available to be used as margin. On the other hand, if the number is negative, then you need to deposit funds to your Groww Balance.
What is the simple formula for margin? ›To calculate profit margin, start with your gross profit, which is the difference between revenue and COGS. Then, find the percentage of the revenue that is the gross profit. To find this, divide your gross profit by revenue. Multiply the total by 100 and voila—you have your margin percentage.
What are examples of margin? ›For example, if you had $5,000 cash in a margin-approved brokerage account, you could buy up to $10,000 worth of marginable stock: You would use your cash to buy the first $5,000 worth, and your brokerage firm would lend you another $5,000 for the rest, with the marginable stock you purchased serving as collateral.
Which margin is most important? ›While there are several types of profit margin, the most significant and commonly used is net profit margin, which is based on a company's bottom line after all other expenses, including taxes, have been accounted for.
How do you use margins in design? ›Change margins and column guides
Choose Layout > Margins and Columns. Enter values for Top, Bottom, Left, and Right Margins, as well as the number of columns and the gutter (the space between columns).
Margin measures how much of every dollar in sales, you keep after paying expenses. The higher your margin, the more money you make. The larger the retail margin, the greater the profit you can make on each sale.
How many types of margins are there in CSS? ›CSS Margin Constituent Properties
There are four margin properties, one for each side of the HTML element box. margin-top: adds margin space on top of the element. margin-right: adds margin space on the right of the element. margin-bottom: adds margin space on the bottom of the element.
The width and height properties include the content, padding, and border, but do not include the margin.
Do CSS margins overlap? ›In CSS, adjacent margins can sometimes overlap. This is known as “margin collapse”, and it has a reputation for being quite dastardly. Instead of sitting 48px apart, their 24px margins merge together, occupying the same space!
What does padding 100% mean? ›
Padding-top property in percent is determined by div width. So, your child is getting 100% width of parent (30%) and padding top 100% means 100% width of that element. The same applies to margin-top which is calculated by width.
What is padding vs margin vs border vs? ›Padding - The inner space between the content and the border of your box. Border - The perimeter of the box. Borders can be invisible or they could be a thick colored line like the green one pictured above. Margin - The outer space (or lack of space) surrounding the box.
What is the difference between padding and width in CSS? ›Width is the space from left to right that the element takes up on the page. Padding is the space around the content of the element (all four sides) but inside of the border.
What does margin 10px mean? ›One way to do this is to add margins, which will create space around one or more sides of the element. A simple margin declaration might look like this: margin: 10px; That declaration means that the margin box should extend 10px in all four directions—left, right, up, and down—beyond the size of the border box.
What is the default margin size in CSS? ›By default, the left and right margins of a text element are set to 0 , but they all come with a margin-top and margin-bottom .
What is the default margin in CSS? ›The default <body> margin is 8px in HTML. It is defined in pixels by the user-agent-stylesheet your browser provides. Some browsers allow you to create and use your own user-agent-stylesheet, but if you are developing a website, keep it the same.
What size margins should you use on all four sides? ›Margins and spacing: Leave margins of at least one inch on all sides of your paper. Page numbers will appear within the top margin, but no other text should extend into the margins. Indent five to seven spaces to begin paragraphs. Double-space the text of your paper.
How do I control line spacing in CSS? ›Use the line-height property in CSS to do so. Browsers by default will create a certain amount of space between lines to ensure that the text is easily readable. For example, for 12-point type, a browser will place about 1 point of vertical space between lines.
What is the difference between margin-top and margin-bottom? ›The margin-bottom specifies the bottom margin of an element. The margin-top specifies the top margin of an element. The margin-left specifies the left margin of an element. The margin-right specifies the right margin of an element.
What is the best line spacing CSS? ›Line spacing should be at least a space-and-a-half within paragraphs. So around 150 percent or 1.5 times the font size. Spacing following paragraphs should be at least two times the font size. Spacing between letters should be at least 0.12 times the font size.
Should I use REM or PX for padding? ›
Just use rems!
Of course, there will be cases in which pixels actually are better. For example, if a user is on a small screen, it's possible that using rems for padding and margin may actually make the experience worse due to the limited space.
Cellpadding basically defines the space present between a table cell's border and the content present in it. Cellspacing basically defines the space present between individual adjacent cells.
Does width override margin CSS? ›The width property sets the width of an element. The width of an element does not include padding, borders, or margins!
How do you avoid margin collapse? ›How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.
What is margin and padding explain with example? ›Margin is said to be the outer space of an element, i.e., the margin is the space outside of the element's border. Padding is said to be the inner space of an element, i.e., the padding is the space inside of the element's border. We can set the margin to auto.
How does the margin property work? ›The margin property defines the outermost portion of the box model, creating space around an element, outside of any defined borders. Thus, if only one value is defined, this sets all four margins to the same value. If three values are declared, it is margin: [top] [left-and-right] [bottom]; .
Why is margin 0 auto not working? ›The most common reason why using margin:auto is not working for your designs is that the element's display property is inline. This applies to elements like <span> , <strong> , <em> , etc. With inline elements, they do not inherently have a width and therefore using margin auto will not work.
How do you set margins at 15 and 70? ›Select Layout > Margins. Select Custom Margins. In Margins, use the Up and Down arrows to enter the values you want. Select OK when done.
What are margin rules? ›Under these rules, as a general matter, the customer's equity in the account must not fall below 25 percent of the current market value of the securities in the account. Otherwise, the customer may be required to deposit more funds or securities to maintain equity at the 25 percent level (referred to as a margin call).
What does a 20% margin mean? ›The profit margin is a financial ratio used to determine the percentage of sales that a business retains as earnings after expenses have been deducted. For example, a 20% profit margin indicates that a business retains $0.20 from each dollar of sales that it makes.
What is the right way to calculate margin? ›
To calculate profit margin, start with your gross profit, which is the difference between revenue and COGS. Then, find the percentage of the revenue that is the gross profit. To find this, divide your gross profit by revenue. Multiply the total by 100 and voila—you have your margin percentage.
What is the difference between margin auto and margin 0? ›margin:auto; You can set the margin property to auto to horizontally center the element within its container. margin:0; if you write only 0 you set all margins to 0 independent of window/Browser size.
Why doesn t margin-Right work? ›There is nothing wrong with the margin-right itself. You cannot see the effect of margin-right because the 'width' property of div causes the margin of div to have more than 10px distance from the right wall of the body. Consequently, it causes the margin-right property not to have any visual effect.
What percentage should your margins be? ›As a rule of thumb, 5% is a low margin, 10% is a healthy margin, and 20% is a high margin. But a one-size-fits-all approach isn't the best way to set goals for your business profitability. First, some companies are inherently high-margin or low-margin ventures. For instance, grocery stores and retailers are low-margin.
How can I improve my margins? ›- Track efficiency. ...
- Develop sales strategies. ...
- Increase customer retention and lead conversion. ...
- Evaluate revenue streams. ...
- Reduce costs. ...
- Invest in development. ...
- Eliminate low-performing goods. ...
- Inspire staff.
Higher operating margins are generally better than lower operating margins, so it might be fair to state that the only good operating margin is one that is positive and increasing over time. Operating margin is widely considered to be one of the most important accounting measurements of operational efficiency.
What is the difference between padding and margin border in CSS? ›Borders: Differences. The main difference between CSS padding and margin is that padding is the space between the element's content and border (within the element itself), while margin is the space around the border of an element. Padding is a CSS property that works only on elements that have borders.
Is using to margin CSS bad? ›The short answer is no, as long as you are only using negative CSS margins to bring elements closer together than their box model properties would allow.