css margin first or padding first? - css

In CSS code,
we use
#testing{
margin: 0;
padding: 0;
}
i use RECESS to code qualify my css file
it suggest me to use padding first and margin after
#testing{
padding: 0;
margin: 0;
}
My question is, does the order of padding and margin important in css quality?
And what's the different between padding first and margin first?
EDIT
just wondering why it suggest the order for me

My question is, does the order of padding and margin important in css quality?
I consider the reason is "coding style".
In order to readability, consistency, manage, picky...
You can also order by a-z, type, css3 last...etc.
And what's the different between padding first and margin first?
Looks.
Example:
WordPress CSS Coding Standards
Google HTML/CSS Style Guide

Margin is applied to the outside of you element hence effecting how far your element is away from other elements.
Padding is applied to the inside of your element hence effecting how far your element's content is away from the border.
Also, using margin will not affect your element's dimensions whereas padding will make your elements dimensions (set height + padding) so for example if you have a 100x100px div with a 5px padding, your div will actually be 105x105px

The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content from top to bottom.
i.e. immediately on top content it takes padding value, border and finally on top of everything margin would come.
Margin,padding and border values should be deducted from the width before assigning the width value in css. For example width: 100px, padding: 10px, margin: 10px, border: 5px means width of the total container is 150px(100px+20px (left and right padding each 10px) + 10px (left and right border 5px each) + 20px (left and right margin)).
order of giving padding and margin values doesn't make any difference. we can write in any order in css.

Related

Strange behavior on computed height and childrens margin

I want to know the real height of an element no matters what it have inside. That's easy. The problem began when I put away the borders of the element and notice an strange behavior, see it here:
http://jsfiddle.net/LypZR/
First div: 122px: OK (children height 100px, children margins 20px, border 2px)
.bordered {
border: 1px solid #000;
}
Second div: 120px: OK (children height 100px, children margins 20px)
.display-inline-block {
display: inline-block;
}
Thirth div: 100px: What? where are the margins?
I solved it using display: inline-block that works just fine for me (in this particular case). But I really want to know what is exactly happening.
I think you're getting surprised by margin collapsing.
The two cases that margins collapse are between adjacent sibling elements and between parent and child elements.
In your case, it's the parent/child collapse that's causing you grief: If you have nothing interesting between the top margin of your parent and the (top margin of its first child|bottom margin of its last child), the parent margin collapses. The transparent border hack is commonly-used in these cases.
You probably noted that it didn't change the actual layout values--the p tag's margin kept the visible elements from collapsing into each other. But I admit it's counterintuitive.
That's called the margin collapsing.
When the child element is given margin and parent element don't have any content in it, this happens.
add this class and its done.
.no-bordered{
overflow:auto;
}
Fiddle : http://jsfiddle.net/LypZR/3/
you can see real height without any collapse if you use the right css selector for all the elements *, so:
* {
height: 100px;
margin: 10px;
}
Like you did it's like a quirk behave for me because I don't know .element selector, and if you look inside the consolle could you see that no margin is applied in the styles tab, but only a computed height is calculated, perhaps for some strange behavior it isn't suppouse to work right. till I know only height width and padding are considerate for real element dimensions.
margins should not be considerate for real element dimensions, this is only an IE issue who do such calc adding margin to real element dimensions. jsfiddle

CSS3 box-sizing: margin-box; Why not?

Why don't we have box-sizing: margin-box;? Usually when we put box-sizing: border-box; in our style sheets we really mean the former.
Example:
Let's say I have a 2 column page layout. Both columns have a width of 50%, but they look kind of ugly because there's no gutter (gap in the middle); Below is the CSS:
.col2 {
width: 50%;
float: left;
}
To apply a gutter you might think we could just set a right margin on the first of the 2 columns; something like this:
.col2:first-child {
margin-right: 24px;
}
But this would make the second column wrap onto a new line, because the following is true:
50% + 50% + 24px > 100%
box-sizing: margin-box; would solve this issue by including margin in the calculated width of the element. I would find this very useful if not more useful than box-sizing: border-box;.
Couldn't you use width: calc(50% - 24px); for your cols? Then set your margins.
I think we could have a box-sizing: margin-box. The css box model shows exactly, what are the positions of the margins of the frames.
There are minor problems - for example, the margin boxes can overlap - but they aren't hard to solve.
I think, the situation is the same, as we can see with the overflow-x & overflow-y combinations, with the absolut positionied divs in table-cells, with the combination of min|max-width|height with the box-sizing, and so on.
There are features, really simple features, which the browser developers simply doesn't develop.
IMHO, box-sizing: margin-box were a very useful feature. Another useful feature were the box-sizing: padding-box, it exists at least in the standard, but it wasn't implemented in any of the major browsers. Not even in the newest chrome!
Note: #Oriol 's comment: Firefox did implement box-sizing: padding-box. But others didn't, and it was removed from the spec. Firefox will remove it in version 50. Sad.
The guy at the top is asking about adding margin to the overall width, including padding and border. The thing is, margin is applied outside the box and padding and border aren't, when using border-box.
I have tried to achieve the border-margin idea. What I have found is that if using margin you can either add a class of .last to the last item (with margin, then apply a margin of zero, or use :last-child/:last-of-type). Or add equal margins all the way around (similar to the padding version above).
See examples here: http://codepen.io/mofeenster/pen/Anidc
border-box calculates the width of the element + its padding + its border as the total width. So if you have 2 divs which are 50% wide, they will be adjacent. If you add 8px padding to them, then you will have a gutter of 16px. Combine that with a wrapping element - which also has padding of 8px - you will have a nicely laid out grid with equal gutters all the way around.
See this example here: http://codepen.io/mofeenster/pen/vGgje
The latter is my favourite method.
I'm sure all of this is obvious, but I'll type it out anyway because...well, I need the exercise. Would the following outcome not be just as efficient as box-sizing: margin-box;:
.col2 {
width: 45%;
height: 90%;
margin: 5% 2.5%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
float: left;
}
http://jsfiddle.net/Fg3hg/
box-sizing is used to control from which point the padding and border are assessed to the overall size of the element. So while it's not kosher to include px margins with a % width (as is usually always the case), it's easier to calculate what the relative percentage amount should be because you don't have to incorporate padding and borders to the defined width.
This is because the box-sizing attribute refers to the size of an element after computing the given dimension-specific values (padding, borders). "box-sizing: border-box" sets the height/width of an element and takes into consideration the padding as well as the border width. The scope of an element's margin is greater than the element itself, meaning it modifies the flow of the page and its surrounding elements, therefore directly altering the way the element fits within its parent relative to its sibling elements. Ultimately a "margin-box" attribute value would cause major problems and is essentially the same as setting the elements height/width directly.
Dimensions of block-level, non-replaced elements in normal flow must satisfy
margin-left + border-left-width + padding-left + width + padding-right + border-right-width + margin-right = width of containing block
When over-constrained, browsers must adjust either the left or right margin.
I think that means the width of the margin box must equal the width of the containing block (i.e. 100%).
For your case, transparent borders with box-sizing: border-box can work much like margins.
On Codrops there are a couple of good articles on the subject of the effect of margins and row's forced to overflow. They suggest using the rem or em unit with a normalizer css setting font size to 100% for all browsers, then when you set widths and margins it is easy to keep track of the effect on the row's width by simply making a note in comments for the total width. A conversion of 16px to 1 em is the way to calculte the targeted viewports total witdh.
Working like that for the dev stage at least and then if you want 'responsive' templates you can convert widths to % including the margin widths.
The other and often simpler way they suggest to handle gutters is to use the pseudo after and the content: ''; on each of your columns which I find works really well. If you set a div class that is the defined last column such as end you can then target that class not to have the pseudo after, or to have a wider one; which ever best suits your layout.
The added bonus of using this pseudo element method is it also gives you a target for shadows that can give a more 3d effect and greater depth to the flat image on the readers monitor as well. I am experimenting with this effect at the moment by scaling up the effects being used on buttons, 'tweaking' the gradients, and the z-index.
Perhaps set the border to 0% opacity using RGBA and use the border as a margin.
There interesting situation when using box-sizing inside body content
no content no border box gives no any value on left-right margin % recount of this two box recount algoritms
.body{
box-sizing: border-box;
margin:0 3%;
}
Firefox versions before 57 also supported the padding-box value for
box-sizing, though this value was been removed from the specification
and later versions of the browser.
So margin-box even not planned...
There should be a box-sizing: margin-box;
But does the following work:
Put a div around it with
.divX{
width: XX%;
display:flex;
align-items: center;
justify-content: center;
}

Why are two elements only 50 pixels apart when the top element has a 50px margin-bottom and the bottom element has a 50px margin-top?

I need to make sure that two elements always 100 pixels apart. There are no errors with my code, but for some reason the margin-bottom on the the P tag is set to 50 pixels and the margin-top on a DIV below it is also set to 50 pixels.
Instead of being a total of 100px apart, they are only 50. Can someone explain this? I do not have any floats on the page so it's not due to a clearing issue. All html and css has been validated.
This happens in the latest version of Chrome and FIrefox 3.6.
Here's an example of my code:
#content p {
margin-bottom: 50px;
}
#content #posted {
border-top: 1px dotted #ccc;
line-height: 20px;
margin-top: 50px;
}
Margins overlap on top of each other. The maximum margin of the elements will be the margin between two elements.
If this is not what's happening in IE, it's an IE bug, as this is how CSS was designed to work.
You could use padding instead, or just make sure the margin of both elements is 100px.
Margins do not stack like that. The bottom element only sets a 50px margin from the top element, not the top element's margin. Therefore you need to make the margins 100px.

CSS, nested divs & margins vs. padding

i totally understand the box model. this question is more about trying to pin down a semantic methodology regarding when to use margins and when to use padding.
here is a typical example,
first, in plain English:
situation: we have a container div, inside of which there is a paragraph element.
goal: to have a 12px space between the inside of the div and the outside of the paragraph.
option a) apply 12px of padding to the container div
option b) apply 12px margins to the paragraph element
or, if you prefer, HTML:
<div id="container">
<p>Hello World!</p>
</div>
and, CSS:
option a)
div#container {padding: 12px;}
option b)
p {margin: 12px;}
Cheers!
Jon
Paddings and margins gives the same effect, Except in the following cases (I might miss some):
You have some kind of background properties. Margins won't get them.
You have a border
You use TD (no margins)
Two nested items, The margins are collapsed together, where paddings not.
(need to check this one) They probably affect the width and height of the element differently. (If some one knows better, pls edit this).
Personally, I prefer option A. Why? Say now I have to add other HTML elements into the div and I want the padding to be maintained, I would not have to add other rules to my CSS files to get it working.
This is a bug in css,
here are examples:
http://creexe.zxq.net/div-issue-padding.html = padding issue
http://creexe.zxq.net/div-issue-margin.html = margin issue
the red and green div tags in the examples were created by the css property TOP,but it has its own disadvantages athat TOP,BOTTOM etc works only when the position of the div tag is Absolute and relative, but not static
It depends on what you're trying to accomplish visually. Would container have other child elements which might hang over into the gutter on either side of the paragraph? If so, a margin makes more sense. But if container should have a 12-pixel gutter for all elements, period, it makes the most sense to use the padding to avoid having to apply margins to multiple element sets.
Generally speaking you always want paragraphs to have vertical margins to ensure consistent paragraph leading.
Personally, I'd go with option a of #container {padding: 12px;} because it makes amply clear that all child elements must stay 12px away from the border of this div.
If I want other elements to stay more than 12px away from the #container's border, then I apply as much more margin to that element.
Cheers!
Vertical padding on the division - because if I decided I wanted a different amount of vertical space in between the multiple paragraphs I'd use bottom margins, and the top/bottom padding of the enclosing division pretty much will always stay intact assuming you just have staticly positioned elements inside.
The difference is where the border sits.
The border sits SMACK DAB in the middle of the margins and padding. If you specify margins, that is white space OUTSIDE the border.
If you specify padding, that is white space INSIDE the border (pushes the border further out from the element)
Can't show you here due to css stripping, but try this out:
<body style="background-color: #aaa">
<p style="background-color: #aee; margin: 40px; padding: 40px; border: solid 2px black;">
i have margins, padding and a border.
</p>
<p style="background-color: #aee; margin: 40px; padding: 0; border: solid 2px black;">
i have margins, and a border.
</p>
<p style="background-color: #aee; margin: 0; padding: 40px; border: solid 2px black;">
i have padding and a border.
</p>
</body>
other stuff!
padding brings in background color of the element, margins are basically transparent
some elements ( like td ) seem to ignore margins, while they respond to changes in padding

What is the difference between `margin` and `padding` in CSS?

What is the difference between margin and padding in CSS?
In what kind of situations:
both work.
only margin is appropriate.
only padding is appropriate.
TL;DR: 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 padding and 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.
div.box > div { height: 50px; width: 50px; border: 1px solid black; text-align: center; }
div.padding > div { padding-top: 20px; }
div.margin > div { margin-top: 20px; }
<h3>Default</h3>
<div class="box">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>padding-top: 20px</h3>
<div class="box padding">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>margin-top: 20px; </h3>
<div class="box margin">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
Margin is on the outside of block elements while padding is on the inside.
Use margin to separate the block from things outside it
Use padding to move the contents away from the edges of the block.
The best I've seen explaining this with examples, diagrams, and even a 'try it yourself' view is here.
The diagram below I think gives an instant visual understanding of the difference.
One thing to keep in mind is standards compliant browsers (IE quirks is an exception) render only the content portion to the given width, so keep track of this in layout calculations. Also note that border box is seeing somewhat of a comeback with Bootstrap 3 supporting it.
There are more technical explanations for your question, but if you want a way to think about margin and padding, this analogy might help.
Imagine block elements as picture frames hanging on a wall:
The photo is the content.
The matting is the padding.
The frame moulding is the border.
The wall is the viewport.
The space between two frames is the margin.
With this in mind, a good rule of thumb is to use margin when you want to space an element in relationship to other elements on the wall, and padding when you're adjusting the appearance of the element itself. Margin won't change the size of the element, but padding will make the element bigger1.
1 You can alter this behavior with the box-sizing attribute.
MARGIN vs PADDING :
Margin is used in an element to create distance between that element and other elements of page. Where padding is used to create distance between content and border of an element.
Margin is not part of an element where padding is part of element.
Please refer below image extracted from Margin Vs Padding - CSS Properties
From https://www.w3schools.com/css/css_boxmodel.asp
Explanation of the different parts:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
Live example (play around by changing the values):
https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel
It's good to know the differences between margin and padding. Here are some differences:
Margin is outer space of an element, while padding is inner space of an element.
Margin is the space outside the border of an element, while padding is the space inside the border of it.
Margin accepts the value of auto: margin: auto, but you can't set padding to auto.
Tip: You can use the trick to make elements centered inside their parents (even vertically). See my other answer for example.
Margin can be set to any number, but padding must be non-negative.
When you style an element, padding will also be affected (e.g. background color), but not margin.
Here is some HTML that demonstrates how padding and margin affect clickability, and background filling. An object receives clicks to its padding, but clicks on an objects margin'd area go to its parent.
$(".outer").click(function(e) {
console.log("outer");
e.stopPropagation();
});
$(".inner").click(function(e) {
console.log("inner");
e.stopPropagation();
});
.outer {
padding: 10px;
background: red;
}
.inner {
margin: 10px;
padding: 10px;
background: blue;
border: solid white 1px;
}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<div class="outer">
<div class="inner" style="position:relative; height:0px; width:0px">
</div>
</div>
The thing about margins is that you don't need to worry about the element's width.
Like when you give something {padding: 10px;}, you'll have to reduce the width of the element by 20px to keep the 'fit' and not disturb other elements around it.
So I generally start off by using paddings to get everything 'packed' and then use margins for minor tweaks.
Another thing to be aware of is that paddings are more consistent on different browsers and IE doesn't treat negative margins very well.
The margin clears an area around an element (outside the border), but the padding clears an area around the content (inside the border) of an element.
it means that your element does not know about its outside margins, so if you are developing dynamic web controls, I recommend that to use padding vs margin if you can.
note that some times you have to use margin.
One thing to note is when auto collapsing margins annoy you (and you are not using background colours on your elements), something it's just easier to use padding.
Advanced Margin versus Padding Explained
It is inappropriate to use padding to space content in an element; you must utilize margin on the child element instead. Older browsers such as Internet Explorer misinterpreted the box model except when it came to using margin which works perfectly in Internet Explorer 4.
There are two exceptions when using padding is appropriate to use:
It is applied to an inline element which can not contain any child elements such as an input element.
You are compensating for a highly miscellaneous browser bug which a vendor *cough* Mozilla *cough* refuses to fix and are certain (to the degree that you hold regular exchanges with W3C and WHATWG editors) that you must have a working solution and this solution will not effect the styling of anything other then the bug you are compensating for.
When you have a 100% width element with padding: 50px; you effectively get width: calc(100% + 100px);. Since margin is not added to the width it will not cause unexpected layout problems when you use margin on child elements instead of padding directly on the element.
So if you're not doing one of those two things do not add padding to the element but to it's direct child/children element(s) to ensure you're going to get the expected behavior in all browsers.
First let's look at what are the differences and what each responsibility is:
1) Margin
The CSS margin properties are used to generate space around elements.
The margin properties set the size of the white space outside the
border. With CSS, you have full control over the margins. There are
CSS properties for setting the margin for each side of an element
(top, right, bottom, and left).
2) Padding
The CSS padding properties are used to generate space around content.
The padding clears an area around the content (inside the border) of
an element. With CSS, you have full control over the padding. There
are CSS properties for setting the padding for each side of an element
(top, right, bottom, and left).
So simply Margins are space around elements, while Padding are space around content which are part of the element.
This image from codemancers shows how margin and borders get togther and how border box and content-box make it different.
Also they define each section as below:
Content - this defines the content area of the box where the actual content like text, images or maybe other elements reside.
Padding - this clears the main content from its containing box.
Border - this surrounds both content and padding.
Margin - this area defines a transparent space that separates it from other elements.
I always use this principle:
This is the box model from the inspect element feature in Firefox. It works like an onion:
Your content is in the middle.
Padding is space between your content and edge of the tag it is
inside.
The border and its specifications
The margin is the space around the tag.
So bigger margins will make more space around the box that contains your content.
Larger padding will increase the space between your content and the box of which it is inside.
Neither of them will increase or decrease the size of the box if it is set to a specific value.
Margin
Margin is usually used to create a space between the element itself and its surround.
for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.
Padding
I usually use when I've an element inside a border, <div> or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.
So briefly, it's situational; it depends on what you are trying to do.
Margin is outside the box and padding is inside the box

Resources