Css 使用百分比定位

Css positioning with using percentage

我是新手,想要一个和this图片一模一样的网页。 但是,我也想用百分比而不是像素来制作 div 的高度和宽度。

当我尝试这样做时,盒子要么彼此重叠,要么根本不出现。因为我的逻辑如下所示。

例如:

  1. Wrapper position:absolute; height:100%; width:100%; (如果我用 px 制作它,没问题但是当我用百分比尝试它时通常我无法得到包装器,为什么?)
  2. header position:relative(相对于 wrapper 的意思?)height:10%; width:100%;
  3. slider position:relative; height:70%; width;100%; top:10%(为什么?因为 10% 被 header 使用,所以它应该从下面的 10% 开始??) ...ETC ...
  4. footer position: relative; height:10%; width:100%; bottom:0; (它必须适合底部)

希望能把我的问题说清楚。 很快,任何人都可以通过我的示例帮助我进行绝对和相对定位吗?

 #wrapper{
 background-color:red;
 height:100%;
 width:100%;
 position: absolute;
  }
 
#header{
 background-color:yellow;
 height:20%;
 width:100%;
 position: relative;

 
 }
 
#slider{
 background-color:blue;
 position: relative;
 height:70%;
 width:100%;
 top:20%;
 
 }
 
#footer{
 background-color:yellow;
 position:relative;
 height:10%;
 width:100%;
 top:90%;
  
}
<html>
<head>
<title></title>
</head>

<body>
<div id="wrapper">
 <div id="header"></div>
 <div id="slider"></div>
 <div id="footer"></div>
</div>
</body>
</html>

这是您的标记的副本,已更新 CSS 以具有 20% 的页眉、70% 的滑块和 10% 的页脚。

里面的divposition: relative所以不用设置任何top,它们会自动堆叠在一起,不需要将 width 设置为默认全角(如 100%)。

虽然使用 position: absolute 时,与 wrapper 一样,需要设置 lefttopwidthheight .

htmml, body {margin: 0; height: 100%; }

#wrapper{
  background-color:red;
  left: 0;
  top: 0;
  height:100%;
  width:100%;
  position: absolute;
  box-sizing: border-box;
}

#header{
  background-color:yellow;
  height:20%;
  position: relative;
  box-sizing: border-box;
}

#slider{
  background-color:blue;
  position: relative;
  height:70%;
  box-sizing: border-box;
}

#footer{
  background-color:yellow;
  position:relative;
  height:10%;
  box-sizing: border-box;
}
<div id="wrapper">
 <div id="header"></div>
 <div id="slider"></div>
 <div id="footer"></div>
</div>

这是一种更现代的方式,使用 flex

html, body {
  height: 100%;
  margin: 0;
}
.wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

header {
  flex: 0;
  flex-basis: 20%;
  background-color: yellow;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
}

main {
  flex: 1;
  flex-basis: 70%;
  background-color: blue;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
}

footer {
  flex: 0;
  flex-basis: 10%;
  background-color: yellow;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
}
<div class="wrapper">

  <header>
    Header
  </header>

  <main>
    Slider
  </main>

  <footer>
    Footer
  </footer>

</div>