Keep

Master CSS Layout

12/15/2017, 7:48:00 AM 4 min read

盒子模型

margin + border + padding + content

定位/浮动

(略)static/relative/absolute/fixed/sticky/float/clear

负外边距(margin)

  • 实现左右布局
<div class="master-css-layout">
  <div class="master-css-layout-main master-css-equal-height">
    <div class="master-css-layout-main-inner"></div>
  </div>
  <div class="master-css-layout-side master-css-equal-height"></div>
</div>
.master-css-layout {
  /*
    1. 超出内容区域隐藏
    2. 清理浮动
  */
  overflow: hidden;
}
.master-css-layout-main {
  /* 让元素浮动,那么它自身与其它相邻元素会在同一行排列 */
  float: left;
  /*
    但,width: 100% 让 main 区域占满整个区域,
    根据上面提到的盒子模型,
    那么 side 就要另起一行排列
  */
  width: 100%;
}
.master-css-layout-side {
  /*
    原本为了和 main 占在同一行,
    这里做了浮动
  */
  float: left;
  width: 32%;
  /*
    *重点*:
    根据上面提到的盒子模型,元素所占宽度尺寸为:
      margin + border + padding + width =>
        -100% + 0 + 0 + width =>
          -100% + 32% => -68%
    计算结果为负值,那么在排版时就不占尺寸(最小值为 0 嘛)
      这样导致的最终结果是 side 和 main 可以在同一行:
        main + side => 100% + 0 => 100%
    但渲染时, margin 需要生效,内容区域正常排版,
      margin 生效,相当于 side 直接向上和 main 开始处重叠,
      内容区域正常排版即可
  */
  margin-left: -100%;
  background-color: beige;
}
.master-css-layout-main-inner {
  /*
    防止由于 side 和 main 重叠,
    导致 main 内容区域不可见,
    添加子元素,并且设置同样大小的 margin 即可
  */
  margin-left: 32%;
  height: 80px;
  background-color: aliceblue;
}
  • 实现两侧等高
<div class="master-css-margin">
  <div class="master-css-margin-side master-css-equal-height"></div>
  <div class="master-css-margin-main master-css-equal-height"></div>
</div>
.master-css-margin {
  /*
    超出内容区域隐藏
  */
  overflow: hidden;
}
.master-css-equal-height {
  /*
    根据上面提到的盒子模型,
      margin + border + padding + height =>
        -1000px + 0 + 1000px + ${height} =>
          ${height}
      ${height} 表示内容区域高度
    得到最终高度为内容区高度,那么父元素的高度为:
      side 和 main 两元素的最大高度
    但在渲染子元素时,子元素很高,会超出父元素区域,
    因此,添加 overflow: hidden 来隐藏子元素超出区域
  */
  padding-bottom: 1000px;
  margin-bottom: -1000px;
}

Flex 模块

建议在 2018 年还不熟悉 Flex 语法的专业前端工程师一定要掌握它,已经是必备技能了。

Grid

相关内容

Tag:
CSS

@read2025, 生活在北京(北漂),程序员,宅,喜欢动漫。"年轻骑士骑马出城,不曾见过绝望堡下森森骸骨,就以为自己可以快意屠龙拯救公主。"