强制元素与兄弟元素的高度相同?

时间:2012-09-18 16:13:26

标签: html css

我有以下标记:

HTML

<div class="container">
    <div class="sidebar">
        info <br/>
        info <br/>
    </div>
    <div class="post">
        post <br/>
        post <br/>
        post <br/>
        post <br/>
    </div>
</div>

CSS

container {
    float:left;
    width:100%;
}
.sidebar {
    float:left;
    clear:both;
    background-color: #eee;
    width:150px;
}
.post {
    background-color: #ccc;
    margin-left:150px;
}

我怎么能强制侧边栏使用HTML / CSS的帖子高度? 侧边栏和柱子的高度都可以改变,但是柱子的高度总是比侧边栏高。

JSFiddle:http://jsfiddle.net/KK4Yc/

4 个答案:

答案 0 :(得分:2)

如果没有JavaScript,除非你用虚假列伪造它,否则不能这样做。如果你想使用jQuery,它是一个单行:

​$('.sidebar').height($('.post').height());​

<强> jsFiddle example

答案 1 :(得分:0)

如果容器具有固定高度,则为是,否则您需要使用JavaScript。

   body, html { height:100% }

    .container {
        width:100%;
        height:500px;
        border:1px solid #ff0000
    }

#bg {
    background-color: #eee;
    width:150px;
    height: 100%;
    position: absolute; 
}
.sidebar {
    float:left;
    clear:both;
    background-color: #eee;
    width:150px;
    height: 100%;
    position:relative;
}

答案 2 :(得分:0)

可以通过JS做,j08691说。 但是您可以尝试不同的方法,例如使用纯css将灰色bg图像添加到.container,因此它看起来像侧边栏延伸到底部,或添加具有相同目的的其他元素({{3 }}):

.container {
    float:left;
    width:100%;
    overflow:hidden;
    position: relative;
}
#bg {
    background-color: #eee;
    width:150px;
    height: 100%;
    position: absolute; 
}
.sidebar {
    float:left;
    clear:both;
    background-color: #eee;
    width:150px;
    height: 100%;
    position:relative;
}


<div class="container">
    <div id="bg"></div>

答案 3 :(得分:0)

好吧我不太确定为什么其他海报会影响他们的长度,你只需要使用dom元素自动拥有的parent->child关系的好处:

.container {
  overflow: hidden;
  border: 1px solid #ff0000;
}

.sidebar {
  background-color: #eee;
  float: left;
  clear: both;
  width: 150px;
}

.sidebar-wrapper {
  background: #eee;
  overflow: hidden;
}

.post {
  margin-left: 150px;
  background-color: #ccc;
}

上面是你应该需要的所有css (只要你有'固定颜色'或'重复背景图像'侧边栏),以下是标记:

<div class="container">
  <div class="sidebar-wrapper">
    <div class="sidebar">
      info <br/>
      info <br/>
    </div>
    <div class="post" style="background: green;">
      post <br/>
      post <br/>
      post <br/>
      post <br/>
    </div>
  </div>
</div>

显然(而且非常恼人地从HTML / CSS的角度来看)如果你没有“纯色”或“重复背景”区域,那么你将不得不采用j08691的javascript方法或Diodeus的固定高度容器方法(虽然Diodeus现在似乎已经改变了代码,并且包含了caligula答案的一部分 - 我猜不出意?)

相关问题