1. 可以介绍一下盒子模型吗?
- 有两种盒子模型,分别是 标准盒子模型和
IE
盒子模型 - 分别可以通过设置box-sizing: border-box / content-box;来转换 ,默认是content-box(标准盒子)
- 区别:以宽度为例,主要在于标准盒子模型的width就是指的是单纯content部分的宽度,而IE盒子模型的width是 content宽度+两边的padding+两边的border。因此整个盒子宽度计算的区别就是:
- 标准盒子总宽度 = width + 两边padding + 两边border + 两边margin
- IE盒子总宽度 = width + 两边margin
2. 介绍一下BFC
- 英文全称Block Formatting Context, 也就是块级格式化上下文。
- 意思:指的是一个独立的渲染区域,让处于
BFC
内部的元素与外部的元素相隔离,使内外元素不会相互影响。 - 触发方法(记法: FPOD ,fp:疯婆, od(华为外包)去华为外包是疯了么):
- 设置float:left/right
- 设置position: absolute/fixed
- 设置
overflow值
不为visible,通常是设置为hidden (其实主要就是通过这个来触发BFC)
设置display为inline-block、flex等
4. 应用场景:清除内部浮动、解决上下盒子外边距折叠问题
给父级盒子加overflow:hidden;可以清除盒子内部浮动;
上下盒子的实际距离默认情况为上方盒子的margin-bottom和下方盒子的margin-top的较大值。
而如果想达到距离为margin-bottom + margin-top的效果,可以给上下任一盒子触发BFC,使其分离即可。(例如给任意一个盒子加个overflow-hidden)
3. 有哪些选择器?他们的优先级?
!important > 内联样式 > ID选择器 > 类选择器 = 伪类选择器 > 元素选择器 = 伪元素选择器 > 通配选择器 > 继承样式 > 默认样式
同一级别:后写的会覆盖先写的
id是 100 类是10 元素 1 权重可以累加但不会进位
4. 什么是清除浮动,有哪些清除浮动的方法?
设置浮动的元素会脱离文档流,不占位置,可能会引起布局混乱。清除浮动是为了让他们占位置,方便布局。
方法一:给父元素加overflow:hidden;触发BFC,清除内部浮动
【但如果内部溢出部分不想隐藏呢】
<style>
.container{
overflow:hidden;
}
</style>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
方法二:在浮动元素后面添加 clear:both
的空 div
元素 【多加个没什么用的div感觉也不太好】
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div style="clear:both"></div>
</div>
方法三:使用伪元素。最推荐也最常用,本质是方法一的优化。【完美且常用】
<style>
.clearfix::after{
content: "";
clear: both;
display: block;
}
</style>
<div class="container clearfix">
<div class="left"></div>
<div class="right"></div>
</div>
5. 垂直水平居中的方法有哪些?
如果是内联元素居中,设置text-align:center(水平居中) line-height = 外部盒子的height (垂直居中)。即可
如果是块级元素居中,有多种方法(一定要熟练)
1. 子绝父相 + transform 【不需要知道盒子宽高】
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2. 子绝父相 + margin 【需要知道盒子宽高 - margin:auto自动算】
.father {
position: relative;
}
.son {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0px;
margin: auto;
height: 100px;
width: 100px;
}
3. flex布局 【display: flex;justify-content: center;align-items: center;三连】
【不需要知道盒子宽高】
<style>
.father {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>