开发者

Borders and margins and padding, oh my! (box model)

The box model ought to be simple enough, but I just don't grok it.

Here's a meaningless form

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">开发者_运维技巧
<html>
<head>
<title>Box model test</title>
<link type="text/css" rel="stylesheet" href="test.css"> 
</head>
<body style="position:relative; top=0px; left=0px">
<form action="for_submitted.php" method="post">

<fieldset style="top:0px; left: 0px; width: 128px; height: 64px;">
  <legend> </legend>
  <div class="label" style="top:24px;  left: 16px; width: 81px; height: 14px;">Box 1</div>
</fieldset>

<fieldset style="top:0px; left: 128px; width: 128px; height: 64px;">
  <legend> </legend>
  <div class="label" style="top:24px; left: 64px; width: 22px; height: 14px;">Box 2</div>
</fieldset>

<div class="submit_button" style="top:64px; left:64px;"><input type="submit" name="submitButton" 

value="Submit"></div>

</form>
</body>
</html>

and its CSS

body
{
  background-color: white;
  width: 100%;
  position: relative;
}    

.panel, .label, fieldset
{
  position: absolute;
  font: 8px Arial; 
}

.submit_button
{
  position: absolute;
}

and I expect it to show

.---------..---------.
| box 1   | box 2    |
.---------..---------.

but in MSIE8 (which I am compelled to use) and in FireFox, it shows

.--------..--------.
| box 1  || box 2  |
.--------..--------.

why do they overlap?


There are several problems here. First of all, you need a reset CSS to remove the margin and padding added by the browser's User Agent stylesheet. Something like Eric Meyer's will do.

Secondly, after adding in the reset CSS there still will be some overlapping. This is caused by the borders, the widths of which are not part of width. outline is not affected by this, so I'm using that in the demo below to show that the elements are not actually overlapping, but I won't recommend using that in place of border. Instead, you should take into account the width of the border when doing your calculations.

See: http://jsbin.com/ofusa3/edit

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜