跳到主要内容

floats

float 布局

float 布局

  • float 属性;
  • 设置 floats 布局;
section {
float: none;
float: left;
float: right;
float: inline-start;
float: inline-end;
}

float 和 normal flow 的关系

  • float 所属标签与 normal flow 分离;
  • float 所属标前在 normal flow 层级之上;

浮动问题

  • float 脱离了 normal flow;
  • float 对应标签 normal flow 中的 content box 造成影响,但是无法影响其 padding 和 margin box;
  • 产生了所谓的 float 问题;

float 问题

清除浮动

clear 属性
  • 决定标签是否移动至其之前的 floating 标签底部;
.left {
border: 1px solid black;
/* 不移动 */
clear: none;
/* 左侧浮动标签底部 */
clear: left;
/* 右侧浮动标签底部 */
clear: right;
/* 左右侧标签底部 */
clear: right;
/* 逻辑属性 */
clear: inline-start;
clear: inline-end;
}
clearfix hack
  • 使用 .wrapper::after 生成一个空的子标签;
  • 由于其是块级标签,况且 clear 属性值为 both;
  • 所以该子标签必须在 floating 子标签底部;
  • 从而拉高了其父标签 .wrapper 标签的高度;
  • 达到清除浮动的效果;
.wrapper::after {
content: "";
clear: both;
display: block;
}
overflow
  • overflow 创建一个块级上下文 (BFC);
  • 非 visible 即可;
.wrapper {
background-color: rgb(79, 185, 227);
padding: 10px;
color: #fff;
overflow: auto; /* other than visible */
}
display
  • 创建块级上下文;
  • display 推荐设置为 flow-root;
    • flex/grid 亦可;
.wrapper {
background-color: rgb(79, 185, 227);
padding: 10px;
color: #fff;
display: flow-root;
}