css实现左侧固定宽度,右侧宽度自适应

来源:互联网 发布:重庆干部网络培训学院 编辑:程序博客网 时间:2024/06/13 10:35

1,固定宽度区浮动,自适应区不设宽度而设置 margin

<!DOCTYPE html>  <html>      <head>        <style type="text/css">        #wrap {            overflow: hidden; *zoom: 1;          }          #content ,#sidebar {            background-color: #eee;           }          #sidebar {            float: left; width: 300px;          }          #content {            /*float: right;此处不能写浮动,否则会脱离文档流*/            margin-left: 310px;          }          #footer {background-color: #f00;color:#fff; margin-top: 1em}        </style>    </head>    <body>        <div id="wrap">          <div id="sidebar" style="height:340px;">固定宽度区</div>          <div id="content" style="height:340px;">自适应区</div>        </div>        <div id="footer">后面的一个DIV,以确保前面的定位不会导致后面的变形</div>    </body> </html>

无论content和sidebar谁更长,都不会对布局造成影响.
这里写图片描述
这里写图片描述
2,固定宽度区使用绝对定位,自适应区照例设置margin

<!DOCTYPE html>  <html>      <head>        <style type="text/css">                  #wrap {            *zoom: 1; position: relative;          }            #content ,#sidebar {                    background-color: #eee;                   }          #sidebar {position: absolute; left:0; top: 0;width: 300px;          }          #content {           margin-left: 310px;          }        #footer {background-color: #f00;color:#fff; margin-top: 1em}        </style>    </head>    <body>        <div id="wrap">          <div id="sidebar" style="height:340px;">固定宽度区</div>          <div id="content" style="height:240px;">自适应区</div>        </div>        <div id="footer">后面的一个DIV,以确保前面的定位不会导致后面的变形</div>    </body> </html>

这里写图片描述
footer说——我不给绝对主义者让位!所以要注意footer的设置。
3.标准浏览器的方法
w3c标准早就为我们提供了制作这种自适应宽度的标准方法。那就简单了:把wrap设为display:table并指定宽度100%,然后把content+sidebar设为display:table-cell;然后只给sidebar指定一个宽度,那么content的宽度就变成自适应了。

<!DOCTYPE html>  <html>      <head>        <style type="text/css">                  #wrap {            display:table;            width: 100%;          }            #content,#sidebar {                    background-color: #eee;                     display: table-cell;                  }          #sidebar {            width: 300px;           }          #content {          margin-left: 10px;          display: block;          } #footer {background-color: #f00;color:#fff; margin-top: 1em}        </style>    </head>    <body>        <div id="wrap">          <div id="sidebar" style="height:240px;">固定宽度区</div>          <div id="content" style="height:340px;">自适应区</div>        </div>        <div id="footer">后面的一个DIV,以确保前面的定位不会导致后面的变形</div>    </body> </html>

这里写图片描述
如果不考虑ie7及以下版本,则使用标准方法;如果不在意sidebar与content的顺序,则用第一种方法

阅读全文
0 0