简体   繁体   English

HTML 中父 div 和子 div 之间存在额外空间

[英]Extra space present between the parent div and child div in HTML

I am placing a div inside another div .我把一个div另一内div Please see the code below JS Fiddle link请参阅下面的代码JS Fiddle 链接

HTML: HTML:

<body>
    <div>
        <div class="wrapper"><div class="set1"></div></div>
    </div>
</body>

CSS: CSS:

* {
  box-sizing: border-box;
}

.wrapper{
  border: 1px solid black;
  padding: 0;
}

.set1{
  width: 100px;
  height: 100px;
  background-color: grey;
  border: 5px solid;
  margin: 0;
}

Here I am expecting the height of parent div = the height of child.在这里,我期待父 div 的高度 = 孩子的高度。 But that's not the case as seen in fig below.但如下图所示,情况并非如此。 I have applied box-sizing : border-box hence the border for the parent should be included in it's height but is not the case.我已经应用了box-sizing : border-box因此父级的边框应该包含在它的高度中,但事实并非如此。 Can you please explain?你能解释一下吗? Also how can I make the child to fully occupy the parent in such case?在这种情况下,我怎样才能让孩子完全占据父母?

在此处输入图片说明

It is because of border(1px each side), use maybe outline instead.这是因为边框(每边 1px),可能使用轮廓代替。

set1集1

集1

wrapper包装纸包装纸

As already mentioned, you are using a border on wrapper which adds these 2px to height.如前所述,您在包装器上使用边框将这些 2px 添加到高度。

If you want that the wrapper has the same height as the parent, you can use a margin on set1 div.如果您希望包装器具有与父级相同的高度,则可以在 set1 div 上使用边距。

Like this:像这样:

.set1{
  width: 100px;
  height: 100px;
  background-color: grey;
  border: 5px solid;
  margin: -1px 0;
}

So the margin should always have the height of the wrapper border.因此边距应始终具有包装边框的高度。 Here your working fiddle: https://jsfiddle.net/gzs9u7m2/2/这是你的工作小提琴: https : //jsfiddle.net/gzs9u7m2/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM