保持相同高度的列

时间:2014-11-04 11:21:37

标签: css twitter-bootstrap twitter-bootstrap-3

我正在尝试使用display: table保留两个相同高度的列。我做了什么:

.col-sm-12
   aside
   .main-content

和CSS

.col-sm-12{
  display: table;
  height: 100%;
}

aside{
  display: table-cell;
  height: 100%;
  width: 25%;
  background: green;
}

.main-content{
  display: table-cell;
  height: 100%;
  width: 75%;
}

工作得很好。但是,当我将内容添加到一边时,内容就会消失。

3 个答案:

答案 0 :(得分:3)

首先,您应该使用Bootstrap网格而不是百分比宽度。

那就是说,为了让两个浮动(和动态)列具有相同的高度,你可以使用这个技巧:

  • 在列父级
  • 上设置overflow: hidden
  • margin-bottom: -5000px; padding-bottom: 5000px添加到列

工作示例(我使用-xs代替-sm仅用于示例目的):



.wrapper {
  overflow: hidden;
}
aside{
  background: forestgreen;
  padding-bottom: 5000px;
  margin-bottom: -5000px;
}
.main-content{
  background: tomato;
  padding-bottom: 5000px;
  margin-bottom: -5000px;
}

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-xs-12">
  <div class="row wrapper">
    <aside class="col-xs-3">
      Aside<br>
      Aside<br>
      Aside<br>
      Aside<br>
      Aside<br>
      Aside<br>
      Aside<br>
      Aside<br>
      Aside<br>
    </aside>
    <div class="col-xs-9 main-content">
      Main content<br>
      Main content<br>
      Main content<br>
      Main content<br>
      Main content<br>
    </div>
  </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

此方法使用边距,填充和溢出来强制列具有相等的高度。该方法需要在每个浮动元素的底部设置足够大的填充,并在相同元素的底部以相等的负边距对抗它。诀窍是将父容器上的溢出设置为隐藏。

这是HTML和CSS:

<div class="main">
<div class="container clearfix">
    <div class="content">
        <section>
            <h1>This is the Main Content</h1>
            <hr>
            <h2>A sub heading</h2>
            <p>Lorem ipsum dolor sit amet, consectetur...</p>
        </section>
    </div>
    <div class="sidebar">
        <aside>
            <h2>This is a sidebar</h2>
            Sign up to the newsletter!
        </aside>
    </div>
</div><!-- /.containter -->

.main .container {
    padding-right: 330px;
    overflow: hidden;
}
.content {
    float: left;
    width: 100%;
    background-color: orange;
}
.sidebar {
    float: right;
    margin-right: -330px;
    width: 300px;
    background-color: olive;
}
.content,
.sidebar {
    padding-bottom: 99999px;
    margin-bottom: -99999px;
}
section,
aside {
    padding: 30px
}

这可以扩展到多行,以获得更像网格的布局,而不仅仅是两列。如果需要,也可以使用流体宽度列。

这是js fiddle Demo

参考链接 http://knowwebdevelopment.blogspot.in/2014/10/css-equal-height-columns-three.html

答案 2 :(得分:0)

将元素的高度设置为100%并不总是有效,因为它会查看其父对象的大小。

这就是我的建议:

<强> HTML:

<div class="row">
    <div class="col-xs-4 tall">25%</div>
    <div class="col-xs-8 tall">75%</div>
</div>

<强>的CSS:

.tall {
    border: 2px dotted black;
    height: 200px;
}

小提琴: My Solution