如何调整容器内的自动宽度?

时间:2015-11-09 10:37:45

标签: html css css3

我有一个内部有3个DIVS的容器:左侧边栏,主要内容和右侧边栏。我希望主要内容具有响应性,因此我将宽度设置为width:calc(100% - 400px);(400px =带有侧边栏)。问题是......如果我隐藏了我的一个侧边栏,主要内容的内容就不会调整。

我想在不将javascript(addClass / removeClass)应用于main-content类的情况下解决此问题。这可能吗?

Fiddle

HTML

<nav><h2>Navigation menu</h2></nav>
<div ng-app="myApp" class="container" ng-controller="myCtrl">

<div ng-hide="showme" class="left-sidebar sidebar">
<h2>Left sidebar</h2>
<hr/><hr/>
  <center><button ng-click="showme=true">Collapse</button></center>
  <hr/><hr/>
</div>
<div class="main-content">
<h1>Documents</h1>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Description</th>
      <th>Sender</th>
      <th>Date</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="json in jsonObj.documents">
      <td ng-bind="json.id"></td>
      <td ng-bind="json.name"></td>
      <td ng-bind="json.description"></td>
      <td ng-bind="json.sender"></td>
      <td ng-bind="json.date"></td>
    </tr>
  </tbody>
</table>
</div>
<div ng-hide="showme2" class="right-sidebar sidebar">
<h2>Right sidebar</h2>
<hr/><hr/>
  <center><button ng-click="showme2=true" >Collapse</button></center>
  <hr/><hr/>
</div>
</div>

CSS

.container {
  width: 100%;
  background: grey;
  height: 200px;
}

.container div {
  height: inherit;
  display: inline;
}

nav {
  background: black;
  height: 50px;
}

nav h2 {
  text-align: center;
  color: white;
  line-height: 50px;
}

.sidebar {
  background: blue;
  width: 200px;
}

.sidebar h2 {
  color: white;
  text-align: center;
}

.sidebar hr {
  margin-top: 25px;
  width: 150px;
}

.left-sidebar {
  float: left;
}

.right-sidebar {
  float: right;
}

.main-content {
  width: calc(100% - 400px);
  background: red;
  float: left;
}

.main-content h1 {
  text-align: center;
}

table {
  margin: 0 auto;
}

table,
thead,
th {
  background: white;
}

table tbody,
tbody,
td {
  background: grey;
}

2 个答案:

答案 0 :(得分:1)

您可以使用table布局。

.container{
   .......
  display: table;
}

.container div{
    .....
 display: table-cell;
 vertical-align: top;
 }
....

.main-content{
  width: 100%;
  background:red;
}

http://jsfiddle.net/afelixj/8q7L3kfy/2/

答案 1 :(得分:1)

您可以使用flexbox。

.container{
  width:100%;
  background:grey;
  height:200px;
  display: flex;
  flex-flow: row wrap;
}

nav{
    background:black;
    height:50px;
}
nav h2{
  text-align:center;
  color:white;
  line-height:50px;
}
.sidebar{
  background:blue;

 max-width:200px;
  flex: 1 auto;
}
.sidebar h2{
  color:white;
  text-align:center;
}
.sidebar hr{
  margin-top:25px;
  width:150px;
}
.left-sidebar{

}
.right-sidebar{

}
.main-content{
  background:red;
  flex: 2 0px;
}
.main-content h1{
    text-align:center;
}
table{
    margin:0 auto;
}
table, thead, th {
    background:white;
}
table tbody, tbody , td {
    background:grey;
}