0

I found that when I mix floated and nonfloated divs, margin of unfloated div is missing.

HTML

<div class="d0 d1">
    Left
</div>
<div class="d0 d2">
    Right
</div>
<div class="d0 d3">
    Center
</div>

CSS

.d0 {
    height: 100px;
    border: 1px solid #333;
}

.d1 {
    float: left;
    width: 100px;
}

.d2 {
    float: right;
    width: 100px;
}

.d3 {
    overflow: hidden;
    width: auto;
    margin: 5px;
}

See this fiddle (5px margin on center div is missing)

http://jsfiddle.net/ozrentk/f5VFc/2/

However, if I add margin to floating elements, then it's really there. Does someone know why is this happening?

EDIT I updated the fiddle, it was a bit confusing To understand the problem, look at the margin that should be BETWEEN Center and Left div. Or Center and Right. There is none.

OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57

1 Answers1

1

The problem you are running into is that a non floated element will ignore floated elements within the document flow. The margin is being applied, but since the non floated div does not recognize the floated one, its is relative to the edge of the page and not the floated div. You can read more about it here: http://spyrestudios.com/css-in-depth-floats-positions/

Joel
  • 5,300
  • 2
  • 14
  • 13
  • It says: *"it’s important to either float all your elements in a container, or none of them"*. How would one then solve the problem when there is left-fixed-width-div, right-fixed-width-div and center div that has to take up the rest of the width? – OzrenTkalcecKrznaric Jul 26 '13 at 19:12
  • Setting a dynamic width on a floated element is rough. It may not be the ideal solution, but you can leave the code the way you have it and set the margin on the center div to be equal to the width of the floated divs + the size of the distance you want between them. So in the example the margin would look like this: margin: 0 105px; – Joel Jul 26 '13 at 19:38
  • @OzrenTkalčecKrznarić Using `display: table-cell`, or redundant exact sizing I imagine. `float` by its nature of being a way to "break the rules" when it comes to element flow is an awkward mechanism that just doesn't offer easy answers to any layout problem you imagine. – millimoose Jul 26 '13 at 19:46
  • @millimoose: damn, that should probably have been the answer to my [previous question](http://stackoverflow.com/questions/17876685/css-four-divs-third-has-to-take-the-rest-of-the-space); however, nobody proposed `display: table-cell`. I'll just have to ask one more hopefully final (for me) question about this kind of div sizing. – OzrenTkalcecKrznaric Jul 26 '13 at 21:06