I use several (in my example 2) div boxes with absolute width (200) on the left and a box with variable width (remaining space) on the right. The boxes on the left are included in a container (divleft), the box on the right is included in divright.
In my example, the right container has a red border. If I remove this border (i.e. change 1px to 0px), then "BOX1" has double its distance to the top of the page - which is 20 pixels (while "BOX RIGHT" is still 10 pixels from the top). If I change the margin of the class "box" from 10px to 5 px, then only "BOX RIGHT" is 5 pixels from the top, while "BOX1" is 10 pixels from the top.
Can somebody please explain this behavior to me?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>TEST</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="0"> <style type="text/css">
You're seeing collapsing margins [w3.org]. This is one of the more confusing topics regarding CSS. Basically, the .box in your right box has a margin of 10px, which pushes #divright down from the top by 10px. Borders and padding will both prevent collapsing margins, so when you add a border to #divright, the margin of .box is contained within #divright instead of forcing #divright down from the top. Without the border, #divleft will get 10px of margin as well (collapsing margins), and then the .box within #divleft adds another 10px of margin, giving the appearance of doubling margins.
One solution would be to add borders or padding to #divright and #divleft. Another solution (better, I think, in that it's easier to maintain) is to add a wrapper div around both columns, and apply the padding to that element instead. For example: