Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does CSS margin work?

Tags:

html

css

In the following code, shouldn't the margin between .box1 and .box2 be 20px as the .box1 has 10px bottom margin and .box2 has 10px top margin.

<div class="box">     <div class="box1"></div>     <div class="box2"></div> </div> 

CSS:

.box1{     margin-bottom: 10px; }  .box2{     margin-top: 10px; } 

http://jsfiddle.net/3C7bW/

like image 876
user2738640 Avatar asked Nov 27 '13 10:11

user2738640


People also ask

How does the margin CSS work?

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 does margin-top work in CSS?

The margin-top CSS property sets the margin area on the top of an element. A positive value places it farther from its neighbors, while a negative value places it closer.

What order do margins go in 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 does 0 margin mean in CSS?

So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered.


2 Answers

No, the margin will only be 10px between the 2 boxes.

You are saying the same thing twice , "that there must be a margin of 10px below box 1" and "that there must be a margin of 10px above box2"

Think of it like this :

There are 2 people, Harry and Sally. Harry is standing 10 feet from Sally. How far is Sally away from Harry? Yep, you got it, 10 feet!

like image 107
CRABOLO Avatar answered Sep 18 '22 12:09

CRABOLO


The bottom margin of the first box and the top margin of the second box are considered to be adjoining; therefore, they collapse into one.

Note that this only applies to vertical margins; horizontal margins never collapse no matter the circumstance. If you made the two boxes float such that they line up horizontally, and gave .box1 a right margin and .box2 a left margin, the total space between them would indeed be 20px.

In fact, even if you didn't line them up horizontally, but floated them and gave them clearance so that .box2 clears .box1, the bottom and top margins would no longer collapse. Both of these cases are mentioned in the spec as well.

like image 22
BoltClock Avatar answered Sep 20 '22 12:09

BoltClock