CSS實現兩列布局,一列固定寬度,一列寬度自適應方法

無論是左是右,反正就是一邊寬度固定,一邊寬度自適應。css

博客園的不少主題也是這樣設計的,個人博客也是右側固定寬度,左側自適應屏幕的佈局方式。html

html代碼:瀏覽器

<div id="wrap">
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定寬度區</div>
  <div id="content" style="height:500px;background:#000;color:#fff;">自適應區</div>
</div>

實現方式方式有以下幾種:ide

1.固定寬度區浮動,自適應區不設寬度而設置 margin

咱們以右側寬度固定,左側寬度自適應爲例:佈局

css代碼:spa

#sidebar {
  float: right; width: 300px;
}
#content {
  margin-right: 300px;
}

實現效果圖:設計

右側一直固定不動,左側根據屏幕的剩餘大小自適應。code

但實際上這個方法是有侷限性的,那就是html結構中sidebar必須在content以前才行htm

但我須要sidebar在content以後!由於個人content裏面纔是網頁的主要內容,我不想主要內容反而排在次要內容後面。blog

那麼上面講解的第一種方法就無效了。

就須要下面的方法來實現。

2.float與margin配合使用

首先咱們調整一下html結構:

<div id="wrap">
  <div id="content" style="height:500px;background:#000;color:#fff;">
    <div class="contentInner">
       自適應區
    </div>
  </div>
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定寬度區</div>
</div>

css代碼:

#content {
  margin-left: -300px; float: left; width: 100%;
}
#content .contentInner{
  margin-left:300px;
}
#sidebar {
  float: right; width: 300px;
}

這樣實現,contentInner的實際寬度就是屏幕寬度-300px。

3.固定寬度區使用絕對定位,自適應區設置margin

html結構:

<div id="wrap">
  <div id="content" style="height:500px;background:#000;color:#fff;">我如今的結構是在前面</div>
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定寬度區</div>
</div>

css代碼:

#wrap{
  position:relative;
}
#content {
  margin-right:300px;
}
#sidebar {
  position:absolute;
  width:300px;
  right:0;
  top:0;
}

4.使用display:table實現

html結構:

<div id="wrap">
  <div id="content" style="height:500px;background:#000;color:#fff;">我如今的結構是在前面</div>
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定寬度區</div>
</div>

css代碼:

#wrap{
  display:table;
  width:100%;
}
#content {
  display:table-cell;
}
#sidebar {
 width:300px;
  display:table-cell;
}

固然最後一種方法在IE7以及如下瀏覽器不兼容,由於IE7設置display爲table不識別。

相關文章
相關標籤/搜索