从双飞翼布局浅谈相关

2017-08-27  本文已影响0人  虚玩玩TT

写一些常见布局的demo

  1. 顶端导航,固定到页面,使用到position: fixed; width: 100%
  2. 两栏布局,一边固定,另一边自适应,直接一边固定宽度,另一边浮动
 <style>
    body {
      margin: 0;
      padding: 0;
    }

    .nav {
      width: 100%;  /*相对于父元素body的宽度,需要清除浏览器默认样式 */
      height: 50px;
      position: fixed;  /*相对于浏览器窗口的绝对定位,实现固定位置*/
      background: black; 
    }

    .cnt {
      max-width: 800px; /*设置最大宽度,响应式*/
      margin: 0 auto;
      padding-top: 50px;
    }

    .cnt1 {
      width: 200px;
      height: 500px;
      background: red;
      float: left;
    }

    .cnt2 {
      height: 500px;
      background: blue;
    }
  </style>

  <div class="nav"></div>
  <div class="cnt">
    <div class="cnt1">cnt1</div>
    <div class="cnt2">cnt2</div>
  </div>

3.三栏布局,两侧固定,中间自适应,两边固定宽度并左右浮动即可,但是在写html的时候需要将中间的“块”写在最后(相对于侧边栏)

<style>
  .main {
    background: blue;
  }

  .aside {
    width: 200px;
    background: red;
    float: left;
  }

  .extra {
    width: 300px;
    background: yellow;
    float: right;
  }
</style>

  <div id="content">
    <div class="aside">aside</div>
    <div class="extra">extra</div>
    <div class="main">main</div>
  </div>

双飞翼布局,利用负 margin 的一些特性。在书写html的时候,中间的“块”写在最前面,并且将中间部分用一个div包裹起来,让div宽度100%,中间块设置margin,给侧边栏留出位置。

<style>
  .wrap,.aside,.extra {
    float: left;
  }  /*先浮动*/
  .wrap {
    width: 100%;  /*将main包裹起来,并设置其宽度为100%,达到自适应效果*/
  }
  .main {
    height: 200px;
    background: blue;
    margin-left: 200px;
    margin-right: 300px;  /*设置左右margin,将侧边栏的位置留出来*/
  }

  .aside {
    width: 200px;
    height: 100px;
    background: red;
    margin-left: -100%;  /*负 margin,定位到相对于content的起始位置*/
  }

  .extra {
    width: 300px;
    height: 100px;
    background: yellow;
    margin-left: -300px;   /*负 margin*/
  }
</style>
  
  <div class="content">
    <div class="wrap">
      <div class="main">main</div>
    </div>
    <div class="aside">aside</div>
    <div class="extra">extra</div>  
  </div>

圣杯布局,和双飞翼布局类似,不过不需要用div包裹中间块,用padding给侧边栏留出位置,依旧是利用了负 margin 的特性。当页面main的宽度过小时,会破坏布局,可以对content设置min-width解决,或者使用双飞翼布局。

<style>
  .content {
    min-width: 350px;
    padding: 0 150px 0 100px;  /*设置padding,数值对应侧边栏的宽度*/
  }

  .content::after {
    content: '';
    display: block;
    clear: both;
  }
  
  .main,.aside,.extra {
    float: left;
  }
  
  .main {
    width: 100%;
    height: 300px;
    background: blue;
  }

  .aside {
    width: 100px;
    height: 100px;
    margin-left: -100%;  /*利用负 margin,定位到相对于content的起始位置*/
    position: relative;  /*使用相对定位调整*/
    left: -100px;
    background: red;
  }

  .extra {
    width: 150px;
    height: 100px;
    margin-left: -150px;
    position: relative;
    left: 150px;
    background: yellow;
  }
</style>
<div class="content">
  <div class="main">main</div>
  <div class="aside">aside</div>
  <div class="extra">extra</div>
</div>
上一篇 下一篇

猜你喜欢

热点阅读