即使在css中使用百分比值,网页元素也会相互重叠



我有一个结构像这样的页面。我想把这个页面分成6个部分,所以我做了6个外部的div

<body>
<div id="header">
  <img />
</div>
<div id="pageTitle">
title of page
</div>
<div id="section1" class="section">
  <div class="section-title">
  section 1
  </div>
  <form>
  <input />
  </form>
</div>
<div id="section2" class="section">
  <div class="section-title">
  section 2
  </div>
  <form>
  <input />
  </form>
</div>
<div id="section3" class="section">
  <div class="section-title">
  section 3
  </div>
  <form>
  <input />
  </form>
</div>
<div id="nav">
<a href="url" />
</div>
</body>

问题是,当我试图通过在firefoxchrome中使用Ctrl++来放大页面时,div s的内容彼此重叠,即使我指定所有属性,如top, width, height, left的百分比。由于百分比是相对单位,所以不应该发生这种情况。

#header {
position:absolute;
top:2%;
width:90%;
height:50%;
}
#pageTitle {
position:absolute;
top:30%;
left:20em;
}
.section {
margin:20px;
border:10px;
width:60%;
height:33%;
}
.section-title {
position:absolute;
font-size:1.4em;
left:70%;
margin:10px;
top:10%;
width:60%;
height:15%
}
#section1 {
position:absolute;
top:40%;
}
#section2 {
position:absolute;
top:70%;
}
#section3 {
position:absolute;
top:100%;
}
form {
position:absolute;
top:30%;
height:70%;
}
label {
display:block;
width:75%;
font-size:1em;
}
#nav {
position:absolute;
top:140%;
}

在我使用像素而不是百分比的其他页面中,内容在放大页面时没有重叠,但像素是绝对单位。怎么了?

像素是屏幕上的点,所以当我放大时像素会变大吗?

这是盒子模型

边距超出宽度和边框。不使用百分比时更容易看出来。

假设你有一个div,它的CSS是:

.myDiv{margin:5px;width:100px;}

实际上在页面上,你的。mydiv是110px宽,110px高。

因为你使用的是绝对定位,浏览器会重叠,因为它会把东西放在你告诉它的地方。希望你能理解。

我建议去掉边距并尝试使用填充来控制间距。如果你想用背景做东西,你可能需要在那里嵌套一个子div并将背景应用到那里以获得相同的效果。

您可以查看W3学校网站的快速和肮脏的概述。

你可以试试下面的css代码来修复

section{
    position: relative;
    height: 100%;
}

最新更新