2013-08-21 53 views
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> 

回答

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/

+0

精彩!我仍然不明白为什么浏览器会提供它在原始版本中的定位,但我可以忍受。 – nttaylor

相关问题