【问题标题】:Margin Top 100% - Height of Parent Div边距前 100% - 父 Div 的高度
【发布时间】:2014-12-20 19:46:21
【问题描述】:

我要构建以下布局:

基本上,我需要三个高度不同且标题高度不同的 div 以 100% 的距离定位到其父级的顶部,减去标题的高度。我可以使用 jQuery 来做到这一点,但这是一个响应式站点,所以我希望它尽可能基于 CSS(否则我将不得不处理 $(window).resize(),根据我的经验,这可能是不可靠的)。

这可能吗,也许使用 CSS3 calc 功能?

谢谢。

【问题讨论】:

  • 标头大小是预定义的还是取决于标头内容长度?

标签: css calc


【解决方案1】:

因此,您可以尝试将内容(橙色容器)添加到蓝色容器的底部(取决于您的 html 结构,您可以在橙色容器中使用 position: absolutemargin-top)。

您可以将标题(绿色)容器放在橙色容器中,并将其放在绝对顶部 -100% 的位置(橙色位置必须是 absoluterelatve)。

如果您将添加您的 html,那么将很容易找到更精确的解决方案。

JSFIDDLE with an example

CSS:

.box{
   background: #f00;
   height: 150px;
   width: 100%;
   position: relative;
   padding: 20px;
   padding-bottom: 0;
}
.column{
    background: #0f0;
    width: 30%;
    position: relative;
    top: 100%
}
.header{
    position: absolute;
    bottom: 100%;
    width: 100%;
    background: #00f;
 }

HTML:

<div class="box">
    <div class="column">
        <div class="header">
           header 
        </div>
        aaaaaaa<br/>
        aaaaaa
    </div>    
</div>

【讨论】:

  • 这是一个很好的解决方案,也很简单。这是我根据 OP 规范对其进行的扩展:jsfiddle.net/zz12cwkf
  • 哇,这个解决方案比我想象的要简单得多。我想我想多了。非常感谢!
【解决方案2】:

我有这个解决方案(适用于任意数量的列,只要它们适合):

  1. 使用内联块使结果居中对齐
  2. 使用相对定位将块与蓝框底部对齐(需要顶部垂直对齐)
  3. 通过将绿色块设置为绝对位置将它们移出流(这会在流中留下与蓝色框底部对齐的橙色框)

body {
  font: medium monospace;
}
.blue {
  background: #AAF;
  height: 12em;
  text-align: center;
}
.helper {
  display: inline-block;
  width: 10em;
  vertical-align: top;
  position: relative;
  top: 100%;
}
.green {
  background: #CFC;
  position: absolute;
  bottom: 100%;
  left: 0;
  right: 0;
}
.orange {
  background: #FCA;
}
<div class="blue">
  <div class="helper">
    <div class="green">
      1<br/>2
    </div>
    <div class="orange">
      1<br/>2<br/>3
    </div>
  </div>
  <div class="helper">
    <div class="green">
      1<br/>2<br/>3
    </div>
    <div class="orange">
      1<br/>2<br/>3<br/>4<br/>5
    </div>
  </div>
  <div class="helper">
    <div class="green">
      1
    </div>
    <div class="orange">
      1<br/>2<br/>3<br/>4
    </div>
  </div>
</div>

【讨论】:

    【解决方案3】:

    尝试以下 CSS 规则:height: calc(100% - header_height);

    【讨论】:

    • 页眉高度从何而来?
    • 嗯。他不知道他的头球高度吗?
    • 他说标题高度不同,你怎么能在css中得到它们
    • 那你是对的,那是行不通的。你知道如何以更好的方式做到这一点吗?如果他不知道标题高度,我不知道该怎么做。
    • 如何计算页眉高度?有人知道吗?