CSS:将边距设置为窗口高度的 10%

标签 css

我正在尝试将绝对定位元素的高度设置为 80%,并将其顶部和底部边距设置为 10%,以便为该元素提供窗口高度的 80%,并在其上方和下方留出 10% 的空间,因为其他元素是出现在那里。

但是正如您在这个 fiddle 中看到的那样 http://jsfiddle.net/qnLC2/ ,并且如 W3C CSS 盒模型规范中所述,所有边距的宽度实际上都设置为窗口宽度(不是高度)的 10%(尝试调整输出屏幕的大小并使其更宽以查看效果)。

W3C CSS 盒模型规范:

The percentage is calculated with respect to the width of the generated box's
containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. 
If the containing block's width depends on this element, then the resulting layout is 
undefined in CSS 2.1.

我想知道是否有任何 CSS only 方法可以解决这个问题。

jsfiddle代码: HTML:

 <div></div>

CSS:

div {
 min-width:20px;    
 min-height:20px;
 background:blue;
 position:absolute; 
 height:80%;
 width: 80%;
 margin:10%;
}
body{
 background:red;   
}

最佳答案

似乎没有任何方法可以仅使用 CSS 来完成。您将需要 javascript,详情如下: Can I set the height of a div based on a percentage-based width?

关于CSS:将边距设置为窗口高度的 10%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13495471/

相关文章:

javascript - 获取位于隐藏父级的元素的尺寸

javascript - iframe 不会消失

HTML Logo 没有响应

css - 使用 Twitter Bootstrap 将元素居中时遇到问题

html - 删除 <a> 标签内文本上下的空格

html - 标题大小不变

jquery - 帮助使用 jQuery 添加类

html - 与图像一起调整 hover_mask 的大小

css - 使 CSS 高度过渡更平滑

javascript - Jquery 花式框错误 404