html布局浅谈

现在布局方式主要分为三种

  • 传统css布局方案(position,float,line-height等配合)。实现复杂,需要多种属性配合使用,兼容性最好。
  • flex布局方案。弹性布局,实现方便,兼容性较好。
  • gird布局方案。

css标准盒模型

尺寸

  • 默认情况: 块级元素宽度默认为100%,高度由内容撑开;内联元素和内联块级元素宽度和高度默认由内容撑开。
  • 开发者设置: 主动设置width、height、line-height等

尺寸的百分比设置

包含块

我们知道width, height都是可以设置百分比,那这个百分比的参照物是谁?这里引出一个概念,叫做包含块(CB, Contanining Block),一个元素的包含块就是该元素的width、height百分比的参照物。

一个元素的包含块是谁,主要取决于该元素的position属性,总结如下:

  • position为static和relative的元素,包含块为其父元素的content-box
  • position为absolute的元素,包含块为其最近的定位非static的祖先元素的padding-box,如果没有定位非static的祖先元素,则为初始包含块(后面解释)
  • position为fixed的元素,包含块为视口viewport
  • position为absolute和fixed时,包含块也可能是由满足以下条件的最近父级元素的padding-box:

    1. A transform or perspective value other than none
    2. A will-change value of transform or perspective
    3. A filter value other than none or a will-change value of filter (only works on Firefox)

margin

块级元素占据一行,是指块级元素的外部尺寸占据一行,就是margin-box。当margin设置为auto的时候,margin会自动占满剩余空间。

  • margin-left: 默认为0,为auto时,自动充满剩余空间
  • margin-right: 默认为0,为auto时,自动充满剩余空间
  • margin-top: 默认为0,为auto时,值还是为0
  • margin-bottom: 默认为0,为auto时,值还是为0

当margin-left和margin-right同时为auto,就会平分剩余空间,这就是margin:auto会使元素水平居中的原因。

line-height和vertical-align

利用line-height和vertical-align可以设置多种场景下的垂直居中。

https://segmentfault.com/a/1190000015713743

原文地址:https://www.cnblogs.com/tiandi/p/12545869.html