css中子元素设置margin-top会影响到父元素

网友投稿 674 2022-05-30

demo代码:

index

div one
content

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

效果

出现问题的地方:

修改content div的margin-top:

.content { width: 100px; height: 100px; background: orange; margin-top: 50px; }

1

2

3

4

5

6

效果

很奇怪,只是修改了content div顶外边距,为什么会影响到父div呢?

CSS的技术文档中有这么一段话:、

In this specification,the expression collasing margins means that adjoining margins(no non-empty content,padding or border areas or clearance separate them)of two or more boxes(which may be next to on another or nested)combine to form a single margin。

大意为折叠边距意味着会邻接两个或多个盒元素的没有非空内容、没有内边距、没有边区域或用间隙分开它们的外边距合并成一个外边距。

以上就是产生这种现象有原因。父元素的第一个子元素的上边距margin-top如果碰不到有效的border或者padding或者非空内容(如一段文字),就会一层一层地合并父元素的margin-top成一个单独的margin-top。因此只要给父元素设置个有效的 border或者padding或在子元素前增加一段非空内容(如文字)就可以阻止它去合并父元素的外边距啦。

解决办法:

1、在子元素添加非空内容

index

div one
Hello World
content

1

2

3

4

5

6

7

8

9

css中子元素设置margin-top会影响到父元素

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

2、父元素增加padding

index

div one
content

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

3、给父元素添加边区域

index

div one
content

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

4、给父元素设置overflow:hidden,auto、scroll、overlay都可以

.content_outer{ width: 500px; height: 500px; background-color: red; overflow:auto; }

1

2

3

4

5

6

5、父元素或者子元素使用浮动或者绝对定位。

谢谢阅读!

CSS

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python下的考勤签到系统
下一篇:GAMES101 学习3——矩阵变换
相关文章