Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the margin work?

I have provided below marginfix which is a block level element and one and two are also block level, but these are floated. That is the reason why they are on same line of layout, but marginfix is not floated either, and block level element should go below the element as the following

+--------------------+                                 +--------------------+
|                    |                                 |                    |
+--------------------+                                 +--------------------+
                        +--------------------------+
                        |                          |
                        +--------------------------+

But it works like this

+--------------------+ +--------------------------+  +--------------------+
|                    | |                          |  |                    |
+--------------------+ +--------------------------+  +--------------------+

This is the HTML

<div class="wrap">
  <div class="one">one</div>
  <div class="two">two</div>
  <div class="marginfix">three</div>
</div>

CSS

.wrap{
  width: 500px;
  background-color: red; 
  position: relative;
  margin: 0 auto;
}
.one{
  width: 200px;
  float: left;
}
.two{
  width: 200px;
  float: right;
}
.marginfix{
  margin: 0 210px;
}

UPDATE NOTE

Someone may say marginfix contain the remaining space of the floated elements. If so, why it wouldn't work if we change the order of the html element. This html won't work as above html

<div class="wrap">
<div class="one">one</div>
<div class="marginfix">three</div>
<div class="two">two</div>
</div>

So how does the margin value work?

like image 359
Navin Rauniyar Avatar asked Apr 30 '13 01:04

Navin Rauniyar


Video Answer


1 Answers

That's how floats work - they are removed from the normal flow of content. If you want to force .marginfix to sit below the others, add .marginfix{clear: both;} to your styles.

like image 186
Mark Parnell Avatar answered Oct 06 '22 20:10

Mark Parnell