【问题标题】:margin-height as percentage of container边距高度占容器的百分比
【发布时间】:2013-08-23 08:37:42
【问题描述】:

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

  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>

【问题讨论】:

    标签: css html containers margin percentage


    【解决方案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 fiddle 来尝试一下:http://jsfiddle.net/maysora/RFevT/

    【讨论】:

    • 太棒了!我仍然不明白为什么浏览器会出现它在我的原始版本中的定位,但我可以接受。
    猜你喜欢
    • 2015-08-12
    • 2012-05-09
    • 2011-06-26
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多