【问题标题】:CSS div height percentage with margin percentageCSS div 高度百分比和边距百分比
【发布时间】:2015-08-12 02:40:48
【问题描述】:

我有一个具有百分比高度和边距的相对 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%。但是,它并没有覆盖父级的所有高度。

这就是我想要的:

这是我得到的:

见小提琴:http://jsfiddle.net/hc3L7ynf/2/

【问题讨论】:

  • 请注意,在水平流中,'margin-top' 和 'margin-bottom' 的百分比是相对于包含块的宽度,而不是高度(在垂直流中,'margin- left' 和 'margin-right' 是相对于高度,而不是宽度)。
  • 您应该使用内边距而不是边距。并且 margin-top 或 margin-bottom 或 padding-top 或 padding-bottom 的百分比与容器的宽度相关,但与高度无关。
  • 谢谢格林先生,我知道了。我认为它会起作用。

标签: css


【解决方案1】:

使用填充代替边距。

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

DEMO

【讨论】:

  • 对不起,但这不是我想要的。我希望孩子的大小是父母的百分之几,并坚持在底部中心。
【解决方案2】:

感谢小提琴的例子。你想要的都可以用

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

【讨论】:

  • 我想要的是将相对 div (.b) 保持在底部,使用组合 margin-top+height=100%。但从小提琴的例子来看,底部有一些空间。
【解决方案3】:

位置棘手

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

.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%;
}
<div class="a">
    <div class="b"></div>
</div>

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

.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%;
}
<div class="a">
  <div class="c"></div>
  <div class="b"></div>
</div>

【讨论】:

  • 这就是我想要的,感谢使用 ::before 的建议。我会试试的,所以我不需要更改 html。
  • @dann 很高兴我能帮上忙
猜你喜欢
  • 1970-01-01
  • 2013-08-23
  • 2013-08-23
  • 2013-04-25
  • 2012-06-19
  • 2012-02-20
  • 2012-05-09
相关资源
最近更新 更多