调整大小时DIV不会缩小

时间:2014-12-31 23:30:58

标签: html css

所以我有一个简单的两个DIV窗格的网站:一个内容区域和一个固定的300px菜单,两者最多都是1200px。我希望用户能够调整窗口大小并使LEFT窗格缩小,同时保持固定的正确菜单。但是现在我找不到任何方法来做到这一点,一切看起来都很好,但是如果我调整窗口大小,左侧窗格不会缩小,而右侧菜单只是包裹在屏幕的底部。使用左侧菜单可以轻松实现,但菜单位于右侧。以下是我到目前为止的情况:

#main
{
 max-width: 1200px;
 margin-right: auto;
 margin-left: auto;
 margin-top: 0;
 display: block;
 padding: 0;
}
#left
{
 max-width: 890px;
 float: left;
 padding-right: 10px;
}
#right
{
 width: 290px;
 top: 0;
 float: right;
 padding-right: 10px;
 padding-left: 10px;
}

2 个答案:

答案 0 :(得分:3)

您可以使用CSS calc()来调整左侧容器的宽度。

OPTION 1 FIDDLE

<强> HTML

<div id="main">
  <div id="left"></div>
  <div id="right"></div> 
</div>

<强> CSS

#main{
  width: 100%; //set to 100% since you're capping it at 1200 anyways
  max-width: 1200px;
  /* margin-right: auto;
  margin-left: auto;
  margin-top: 0; */ condense these to the following:
  margin: 0 auto;
  /*display: block;*/ already a block element so not necessary 
  padding: 0;
  overflow: hidden; //add to correct floating elements
}

#left{
  background: red; //just for my test
  height: 100px; //just for my test
  width: calc(100% - 300px); //readjusts based on screen size
  float: left;
  padding-right: 10px;
  -moz-box-sizing: border-box;  //if you use padding add these lines to fix issue of padding adding to width 
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
 }

 #right{
   background: black; //just for my test
   height: 100px; //just for my test
   width: 300px;
   /*top: 0;*/ //dont need, not doing anything
   float: right;
   /*padding-right: 10px;
   padding-left: 10px;*/ //can condense to following:
   padding: 0 10px;
   -moz-box-sizing: border-box; //see padding explanation above
   -webkit-box-sizing: border-box;
   box-sizing: border-box;
 }

或者

如果您担心旧浏览器,可以使用display: tabledisplay: table-cell执行此操作,如下所示:

OPTION 2 FIDDLE

<强> CSS

#main{
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  display: block;
  padding: 0;
  display: table; //add
  table-layout: fixed; //add
}

#left{
  display: table-cell; //use instead of float
  background: red;
  height: 100px;
  padding-right: 10px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

#right{
  display: table-cell; //use instead of float
  background: black;
  height: 100px;
  width: 300px;
  padding: 0 10px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

答案 1 :(得分:1)

而不是浮动div,请尝试左右窗格中的display: inline-block,或CSS3 flexbox(取决于您支持旧版浏览器的距离)。

Flexbox示例:http://jsfiddle.net/571k3gx2/