CSS div高度百分比与保证金百分比

时间:2015-05-29 09:33:23

标签: css

我有一个百分比高度和边距的相对div。

<div class="a">
    <div class="b"></div>
</div>

.a{
    position:fixed;
    top:0;
    left:0;
    bottom:0;
    right:0;
}

.b{
    position:relative;
    background-color:red;
    height:75%;
    width:92%;
    margin: 25% 4% 0 4%;
}

高度75%和保证金前25%应该加起来达到100%。但是,它并没有涵盖父母的所有高度。

这就是我想要的:
enter image description here
这就是我得到的:
enter image description here

请参阅小提琴:http://jsfiddle.net/hc3L7ynf/2/

3 个答案:

答案 0 :(得分:1)

位置棘手

将固定位置更改为绝对位置可以更轻松地显示问题所在:

&#13;
&#13;
.a{
    position: absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
    border: 1px solid black;
}

.b{
    position: relative;
    background-color:red;
    height:75%;
    width:92%;
    margin: 25% 4% 0% 4%;
}
&#13;
<div class="a">
    <div class="b"></div>
</div>
&#13;
&#13;
&#13;

最简单的解决办法就是在它上面添加一个高度为25%的类; 或使用:: before会做同样的事情。

&#13;
&#13;
.a {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border: 1px solid black;
}
.b {
  position: relative;
  background-color: red;
  height: 75%;
}
.c {
  height: 25%;
}
&#13;
<div class="a">
  <div class="c"></div>
  <div class="b"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

而不是使用填充的边距。

.b{
position:relative;
background-color:red;
height:75%;
width:92%;
padding: 25% 4% 0 4%;
}

DEMO

答案 2 :(得分:0)

感谢小提琴的例子。您可以使用

创建所需内容
.b {
    position:relative;
    background-color:red;
    height:96%;
    width:92%;
    margin: 4% 4% 0% 4%;
}