CSS 几种布局方式.

2019-02-24  本文已影响0人  人话博客

纵向布局

image.png

CSS代码结构

 <style>
    * {
      margin: 0;
      padding: 0;
    }
    div {
      /* 居中 */
      margin: 0 auto;
      /* 宽度一直 */
      width: 800px;
    }

    .header {
      height: 100px;
      background: red;
    }

    .content {
      min-height: 700px;
      background: green;
    }

    .footer {
      height: 100px;
      background: yellow;
    }

  </style>
</head>
<body>
  <div class="header"></div>
  <div class="content"></div>
  <div class="footer"></div>
</body>
image.png
 <style>
    * {
      margin: 0;
      padding: 0;
    }
    .header {
      height: 100px;
      background: red;
    }
    .content {
      width: 800px;
      min-height: 800px;
      background: green;
      margin: 0 auto;
    }

    .footer {
      height: 100px;
      background: yellow;
    }
  </style>
</head>
<body>
  <div class="header"></div>
  <div class="content"></div>
  <div class="footer"></div>
</body>

横向布局

左边宽度固定,右边自适应.

image.png

原理:

左边元素设置固定宽度 200px . 并设置浮动.
右边元素设置成 block(block)默认width就是100%. 并设置 overflow : hidden.
overflow:hidden 会产生一个 BFC(blocking formatting context),特点之一是不会和float元素产生重叠.

<style>
    * {
      margin: 0;
      padding: 0;
    }

    div {
      height: 200px;
    }

    .left-float {
      background: red;
      width: 200px;
      float: left;
    }
    .right-overflow-hidden {
      height: 200px;
      background: green;
      overflow: hidden;
    }
  </style>
</head>
<body>
    <div class="left-float"></div>
    <div class="right-overflow-hidden"></div>
</body>
<style> 
    .parent {
      display: flex;
    }
    .parent .left-child {
      height: 200px;
      width: 200px;
      background: blue;
    }

    .parent .right-child {
      height: 200px;
      flex: 1;
      background: orange;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="left-child"></div>
    <div class="right-child"></div>
  </div>
</body>

粘性布局

当内容的长度不足一屏幕的时候,.footer 设定在屏幕底部.
让内部的长度大于一屏幕的时候,.footer 跟随内容,一直处于内容底部.

image.png
<style> 
    * {
      margin: 0;
      padding: 0;
    }
    html ,body {
      height: 100%;
    }
    .wrapper {
      min-height: 100%;
      background: yellow;
    }
    .wrapper .main {
      padding-bottom: 50px;
      height: inherit;
    }

    .footer {
      height: 50px;
      margin-top: -50px;
      background: red;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="main">
    </div>
  </div>
  <div class="footer"></div>
</body>

说明:

  1. 需要将 html,body 的 height 设置成 100%
  2. 设置 wrappermin-height:100%
  3. 设置 wrapper mainpadding-bottom:50pxfooter 预留空间.并继承 wrappermin-height ,也是最小 100% 的高度.
  4. 设置 .footermargin-top:-50pxfooter 在不足一屏幕的时候,定屏幕下面(有 min-height) 来决定.
  5. 超过一屏幕的时候,利用 main.padding-bottom & footer.margin-top=-50px 来来定住.
上一篇 下一篇

猜你喜欢

热点阅读