如何将子元素高度设置为100%不使用javascript?

时间:2013-05-23 03:57:31

标签: css

我有一个类似下面的html,我想将SIDEBAR高度设置为100%,但我尝试了很多方法并不总是,有人可以告诉我该怎么做吗?

P.S。 我希望是自动高度,而不是设置父元素高度!

<!DOCTYPE html>
<html>
  <head>
      <meta charset='UTF-8' />
      <style>
      * {
        padding: 0;
        margin: 0;
      }
      .wrap {
        overflow: visible;
        height: auto;
      }
      .table {
        background: gray;
        list-style: none;
        display: table;
        width: 100%;
        height: inherit;
      }
      .left {
        background: green;
        display: table-cell;
        height: inherit;
      }
      .right {
        background: blue;
        display: table-cell;
        width: 300px;
        height: inherit;
      }
      .sidebar {
        background: red; 
        height: 100%; /* not working */
        margin: 0;
      }
      </style>
  </head>

  <body>
    <div class="wrap">
      <ul class="table">
        <li class="left">
          <p>content</p>
          <p>content</p>
          <p>content</p>
          <p>content</p>
          <p>content</p>
          <p>content</p>
          <p>content</p>
          <p>content</p>
          <p>more...</p>
        </li>
        <li class="right">
          <div class="sidebar">
            <p>link</p>
            <p>link</p>
            <p>link</p>
            <p>link</p>
            <p>link</p>
            <p>more..</p>
          </div>
        </li>
      </ul>
    </div>
  </body>
</html>

http://jsfiddle.net/cJpb6/

2 个答案:

答案 0 :(得分:1)

如果对象不知道100%是什么,则最初高度100%不起作用。 100%取决于他们的父母。这就是为什么在这个特殊情况下你必须将它添加到表,.wrap,body和html。

html, body {
     height:100%;
}

.wrap {
    overflow: visible;
    height: 100%;
}

.table {
    background: gray;
    list-style: none;
    display: table;
    width: 100%;
    height:100%;
}

.table li {
      height:100%;
      display:table-cell;
}

Jsfiddle:http://jsfiddle.net/YKqB8/

答案 1 :(得分:1)

您正在使用height: inherit;,并且您继承了设置为自动的div的高度,那么当您使用height: 100%;时,却只有100%的内容?您需要将父元素height设置为100%,但由于您要使侧栏占用蓝色空间,您需要为父div指定修复高度,如

.right {
    background: blue;
    display: table-cell;
    width: 300px;
    height: 330px;
 }
.sidebar {
    background: red; 
    height: 100%;
    margin: 0;
}

Demo

如果您希望容器占据整个页面,则需要将所有容器的高度设置为100%,这样侧边栏将成为父元素100%高度的100%

html, body {
    height: 100%;
}

.wrap {
    overflow: visible;
    height: 300px;
    height: 100%;
}

Demo