秦小

CSSMM4E 笔记 - 3.13 - 构建基于浮动的布局

这里有模板:

模板生成器:

CSS 本身有列支持:
https://www.w3.org/TR/css3-multicol/
https://dev.opera.com/articles/css3-multi-column-layout/
http://aaronlumsden.com/multicol/

两列设计的步骤

  1. <div>包裹每一列,设置ID或class属性
    <div class="news"> <div class="main">
  2. 浮动 sidebar div 到左边或右边
  3. 为浮动的 sidebar 设置宽度
  4. 设置 main div 的左或右右 margin

应用浮动的布局

Flaot对内容在html出现的顺序有要求.
让最重要的内容出在html的最前面对search engine更友好.
下面两个方法都可以使主要内容靠前.

  • 浮动所有列
    比如: 3列: 1. Float sidebar1 left; 2. Float main content; 3. Float right sidebar2.
  • 浮动中的浮动
    比如: 3列: 1. Wrap left sidebar and main; 2. Float main right, left sidebar left; 3. Float right sidebar right.

克服浮动(float)的缺陷

Clearing and Containing Floats why?

由于Floating元素下面的元素会包围它, 有时这是我们不期望的.
footer { clear: both; } 解决.

当容器中Floating元素后面没有后继元素/后继元素较短时, 容器会收缩(就当Floating元素不存在).

如下图: 标题”Bathtub…” 与下面两个小section在同一个Container(浅灰色背景)中
由于sections floating, 导致Container Collapse.
三个长条容器, 其中三个img floating, collapse.

解决方案:

  1. 在容器底部加一个 clearing 元素
    缺点: 额外的元素.
  2. 浮动容器元素
    Floating container expands to fit everything inside it. 但Floating向外传递了.
  3. 使用 overflow:hidden
    overflow:hidden到container, 但当container中有absolutely positioned元素是就不适用了.
  4. 使用 Micro Clear Fix(MCF, 清除修复宏)
    1
    2
    3
    4
    5
    .clear:after { /* clear is the class of the container. */
    content: " ";
    display: table;
    clear: both;
    }

创建全高 (full-height) 的列

First other way
Second other way

方法1: 为各列设置背景图片包裹.

1
2
.wrapper1 { background: url(images/col1_bg.gif) repeat-y left top; }
.wrapper2 { background: url(images/col2_bg.gif) repeat-y left top; }

方法2: Wrap all columns and apply gradient across columns.

  1. Wrap all three columns.
  2. Add a linear gradient, with color stop that match the width of the columns.
1
2
3
4
5
6
.wrapper {
background-image: linear-gradient(left,
red 0%, red 25%,
white 25%, white 75%,
blue 75%, blue 100%);
}

防止浮动元素挤落

box-sizing 防止浮动元素被挤落
* { box-sizing: border-box; }