面试题-css布局1

主要有以下问题:

  • 盒子模型的宽度如何计算?
  • margin 纵向重叠的问题
  • margin 负值的问题

问题一:盒子模型宽度计算

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!-- 如下代码,请问div1的offsetWidth 是多大? -->
<style>
  #div {
    width: 100px;
    padding: 10px;
    border: 1px solid #ccc;
    margin: 10px;
  }
</style>

<div id="div1"></div>

提示:offsetWidth = ( 内容宽度 + 内边距 + 边框 ),无外边距

答案: 122px

补充:如果让 offsetWidth 等于 100px,该如何做?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<style>
  #div {
    width: 100px;
    padding: 10px;
    border: 1px solid #ccc;
    margin: 10px;

    // 插入
    box-sizing: border-box;
  }
</style>

问题二:margin 纵向重叠问题

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!-- 如下代码, AAA 和 BBB 之间的距离是多少? -->
<style>
  p {
    font-size: 16px;
    line-height: 1;
    margin-top: 10px;
    margin-bottom: 15px;
  }
</style>

<p>AAA</p>
<p></p>
<p></p>
<p></p>
<p>BBB</p>

提示:

  • 相邻元素的 margin-top 和 margin-bottom 会发生重叠
  • 空白内容的

    也会重叠

答案: 15px

问题三:margin 负值问题

  • 对 margin 的 top left right bottom 设置负值,有何效果?

答案:

  • margin-top 和 margin-left 负值,元素向上、向左移动

  • margin-right 负值,右侧元素左移,自身不受影响

  • margin-bottom 负值,下方元素上移,自身不受影响

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>margin 负值</title>
    <style type="text/css">
      body {
        margin: 20px;
      }

      .float-left {
        float: left;
      }
      .clearfix:after {
        content: "";
        display: table;
        clear: both;
      }

      .container {
        border: 1px solid #ccc;
        padding: 10px;
      }
      .container .item {
        width: 100px;
        height: 100px;
      }
      .container .border-blue {
        border: 1px solid blue;
      }
      .container .border-red {
        border: 1px solid red;
      }
    </style>
  </head>
  <body>
    <p>用于测试 margin top bottom 的负数情况</p>
    <div class="container">
      <div class="item border-blue">this is item 1</div>
      <div class="item border-red">this is item 2</div>
    </div>

    <p>用于测试 margin left right 的负数情况</p>
    <div class="container clearfix">
      <div class="item border-blue float-left">this is item 3</div>
      <div class="item border-red float-left">this is item 4</div>
    </div>
  </body>
</html>