1

这可能是一个老问题,但我找不到答案。我需要的是:

  1. 一个浮动容器 div,其高度随窗口大小而变化。
  2. 内部固定大小的 div,其垂直位置随容器大小而变化。
  3. 另一个固定大小的 div 就在 #2 的下方。

以下代码满足条件#1 和#3:调整窗口大小也会正确调整容器 div 的大小,并且第二个内部 div 正确位于第一个内部 div 下方。

但是条件 #2 不满足。我认为“margin-top”作为百分比会使值根据父容器的高度而变化,但显然它不是那样工作的。调整窗口大小对容器 div 中内部 div 的垂直位置没有任何影响。

这似乎不应该那么难,但它很疯狂!请帮忙!

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>css test</title>
  <style>html, body {height: 100%;}</style>
</head>
<body>
  <div style="height: 50%; width: 100px; float: left; background-color: #C00; text-align: center;">
  <div style="margin-top: 50%; height: 40px; width: 40px; background-color: #0C0;"></div>
  <div style="height: 40px; width: 40px; background-color: #00C;"></div>
  </div>
</body>
</html>
4

1 回答 1

1

添加另一个包装器 div 来包装两个内部 div 以进行定位:

<div style="height: 50%; width: 100px; float: left; background-color: #C00; text-align: center; position: relative;">
    <div style="position: absolute; top: 50%; margin-top: -20px;">
        <div style="height: 40px; width: 40px; background-color: #0C0;"></div>
        <div style="height: 40px; width: 40px; background-color: #00C;"></div>
    </div>
</div>

在这里尝试一下js小提琴:http: //jsfiddle.net/maysora/RFevT/

于 2013-08-21T05:49:52.230 回答