分配div以避免重叠

3
我正在尝试生成一个"A4" html作为保存为PDF的模板,我的页面有5个div覆盖了印刷区域的100%。
我为每个div使用绝对定位,但它们似乎有一点重叠,这是为什么?

 body {
          background: rgb(204,204,204); 
        }
        page[size="A4"] {
          background: white;
          width: 210mm;
          height: 297mm;
          display: block;
          margin: 0 auto;
          margin-bottom: 0.5cm;
          box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
        }
        @media print {
          body, page[size="A4"] {
            margin: 0;
            box-shadow: 0;
          }
        }   
        .area100{
          border:1px solid black;
          position:absolute;
          width:210mm;
        }
        .area50{
          font-size:9px;
          padding:10px;
          text-align: justify;
          border:1px solid black;
          position:absolute;
          width:105mm;
          height:98mm;
          overflow:hidden;
        }
<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
  
</head>
<body>
    <page size="A4">
        <div id="header" class="area100" style="height:20mm;">
        This is header
        </div>
        <div id="main" class="area100" style="height:129mm; top: 20mm;">
        This is main
        </div>
        <div id="bottom-left" class="area50" style="top: 149mm">
        {agreement}
        </div>
        <div id="bottom-right" class="area50" style="left:105mm; top: 149mm">
        right
        </div>
        <div id="footer" class="area100" style="top: 247mm; height:50mm">
        This is footer
        </div>
    </page>
</body>
</html>

1个回答

1

在使用 position: absolute; 时,始终设置 topleft 属性,因为浏览器会尝试猜测它们,有时并不是您想要的。

此外,元素的实际宽度包括 width + padding,因此当您设置 width: 105mm; padding: 10px; 时,实际宽度为 105mm + 20px

body {
  background: rgb(204, 204, 204);
}
page[size="A4"] {
  background: white;
  width: 210mm;
  height: 297mm;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0, 0, 0, 0.5);
}
@media print {
  body,
  page[size="A4"] {
    margin: 0;
    box-shadow: 0;
  }
}
.area100 {
  border: 1px solid black;
  position: absolute;
  top: 0;
  left: 0;
  width: 210mm;
}
.area50 {
  font-size: 9px;
  padding: 10px;
  text-align: justify;
  border: 1px solid black;
  position: absolute;
  width: 99mm;
  height: 98mm;
  overflow: hidden;
  top: 0;
  left: 0;
}
<page size="A4">
  <div id="header" class="area100" style="height:20mm;">
    This is header
  </div>
  <div id="main" class="area100" style="height:129mm; top: 20mm;">
    This is main
  </div>
  <div id="bottom-left" class="area50" style="top: 149mm">
    {agreement}
  </div>
  <div id="bottom-right" class="area50" style="left:105mm; top: 149mm">
    right
  </div>
  <div id="footer" class="area100" style="top: 247mm; height:50mm">
    This is footer
  </div>
</page>


1
就像Justinas所说的那样,如果你查看你的margin-top值,你会发现第一个盒子实际上是从顶部调整了8px,因为body标记带有8px的margin。这将把header div的底部与顶部相距20mm + 8px,依此类推。 - JonasR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接