当父元素没有边框border时,第一个子元素的margin-top和最后一个子元素的margin-bottom,不会计算在父元素的高度内。具体表现如下:

解决方法有四种:1.给父元素加border。
2.给父元素加padding。
3.给父元素加overflow:hidden。
4.(推荐使用) 给父元素加前置内容生成。
- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Documenttitle>
-
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vxe-table@legacy/lib/style.css" />
-
- <style type="text/css">
- #parent{
- width:300px;
- background-color:yellow;
- /*1、给父元素加border*/
- /*border:1px solid black;*/
-
- /*2、给父元素加padding*/
- /* padding-top:10px;*/
-
- /*3、给父元素加overflow:hidden*/
- /* overflow:hidden; */
- }
- /*4、给父元素加前置内容生成*/
- /* #parent:before{
- content:" ";
- display:table;
- } */
- .child{
- width:100px;
- height:100px;
- background-color:red;
- margin:10px 0;
- }
- style>
- head>
-
- <body>
- <div id="parent">
- <div class="child">div>
- <div class="child">div>
- <div class="child">div>
- div>
- <script>
- //第一个子元素的margin-top和最后一个子元素的margin-bottom高度未计算在内
- console.log(document.getElementById('parent').clientHeight) //输出320,正确值是340。
- script>
- body>
-
- html>