CSS面试题

合模型

  • 盒模型

    • W3C标准盒模型:width,height包含content,不包含border和padding
    • IE盒模型:width,height包含border和padding(content+border+padding)
    • box-sizing:设置是什么模型
      • content-box(默认):W3C标准盒模型(content就是content),border,padding会另外加上,导致width和height无法对盒模型的大小进行设置
      • border-box:IE盒模型,width和height都是border+padding+content,这样width和height就可以对盒模型的大小进行设置

margin重叠

相邻的两个盒子或者多个盒子的margin重叠,导致设置margin不符合预期

  • 解决办法

    • 底部的元素设置为浮动float: left
    • 底部的元素设置脱离文档流position: absolute/fixed
    • 统一设置margin-top/margin-bottom

文档流

  • 标准文档流:元素默认自动从左到右,从上到下的排序方式

  • 块级元素:div,li,h1~h4,p

  • 行内元素:span,a,input,select,textarea,img

  • 定位

    • static(默认)
    • relative(相对定位,没有脱离文档流,父级元素使用)
    • absolute(绝对定位,脱离文档流,子级元素使用)
    • fixed(固定到可视视图中的位置,脱离文档流)
    • sticky(粘性定位,滚动到特定位置后固定在可视视图的位置,脱离文档流)

优先级

  • !important > 内联样式style="color: red;" > id#id > 类.foo/伪类:first-child/属性选择器div[class="foo"] > 标签div, h1 > 通配符*

浮动

为什么要清除浮动

  • 防止父元素高度坍塌,因为浮动元素脱离文档流,不再占据父元素的高度。如果父元素只包含浮动元素,父元素的高度会是0,从而影响后续的布局

  • 避免后续元素受浮动元素影响

清除浮动

  • 使用clear属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<style>
.container {
width: 100%;
}

.float-left {
float: left;
width: 50%;
background-color: lightblue;
}

.clear {
clear: both;
}
</style>

<div class="container">
<div class="float-left">Left float</div>
<div class="float-left">Left float</div>
<div class="clear"></div>
<div>Non-floated content</div>
</div>
  • 使用伪元素清除浮动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<style>
.container {
width: 100%;
overflow: hidden; /* 也可以使用 clearfix */
}
.float-left {
float: left;
width: 50%;
background-color: lightblue;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
</style>

<div class="container clearfix">
<div class="float-left">Left float</div>
<div class="float-left">Left float</div>
<div>Non-floated content</div>
</div>
  • 使用overfow属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<style>
.container {
width: 100%;
overflow: hidden;
}
.float-left {
float: left;
width: 50%;
background-color: lightblue;
}
</style>

<div class="container">
<div class="float-left">Left float</div>
<div class="float-left">Left float</div>
<div>Non-floated content</div>
</div>

单位

  • px:像素,浏览器最小是12px,还想要设置更小的话可以使用transform:scale(0.8),但是位置可能会不符合预期,可以使用transform-origin: 0 0设置位置的对齐

  • rem:相对单位,相对于html根节点的font-size的值

元素居中

  • 水平居中使用margin: 0 auto(块级元素)、text-align: center(行内元素)

  • flex布局

1
2
3
4
5
.container {
display: flex;
justify-content: center;
align-items: center;
}
  • grid布局

1
2
3
4
.container {
display: grid;
place-items: center;
}
  • 绝对定位

1
2
3
4
5
6
7
8
9
10
.container {
position: relative;
}

.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}