CSS - 将元素的宽度和高度设置为零

4
有一个padding为30px,宽和高为100px的
元素。box-sizing属性被设置为border-box。当尝试将宽度和高度设置为零时,它不起作用。元素保持60px X 60px 的尺寸(即使overflow属性设置为hidden)。
这是怎么回事?有没有办法使宽度和高度为零,包括padding,使其完全折叠?

.test {
  padding: 30px;
  width: 400px;
  height: 400px;
  box-sizing: border-box;
  background-color: orange;
  overflow: hidden;
}
 
 /* Setting width and height to zero. */
.test {
  width: 0;
  height: 0;
}
<div class="test"></div>
<p>Have a div with padding of 30px and width and height of 100px. Box sizing is set to border box. When trying to set the width and height to zero, it does not work. Element stays at 60px X 60px dimensions. (Even with the overflow set to hidden).</p>
<p>Any idea what's going on here? Is there any way to make the width and height to zero including the paddings, so that it collapses completely?</p>


1
去除填充 - 宽度中包含的填充 - Lalji Tadhani
3
根据CSS盒模型,内边距存在于边框内部。因此,这是正常的行为。 - m4n0
1
如果你想要隐藏,为什么不使用 display:none 呢?你能告诉我需要使用这个的场景吗? - Suresh Ponnukalai
@SureshPonnukalai 我想要将高度从初始值动画到零(包括边框和填充属性),然后将其显示设置为无。试图模仿 $('element').slideUp() 的行为。 - user5279038
在相同的动画中尝试应用padding:0 - Suresh Ponnukalai
显示剩余5条评论
3个回答

4
根据CSS盒模型,内边距位于边框内部。因此,这是正常的行为。如果您想仅在内容存在时显示padding,则可以使用:empty来删除空内容的元素。

.test {
  padding: 30px;
  width: 400px;
  height: 400px;
  box-sizing: border-box;
  background-color: orange;
  overflow: hidden;
}
/* Setting width and height to zero. */

.test {
  width: 0;
  height: 0;
}
.test:empty {
  display: none;
}
<div class="test"></div>
<div class="test">Test</div>


1

padding也包括在高度和宽度内,padding:30px表示左、右、上和下各30像素。这意味着您的div实际尺寸为460X460,因此您需要在覆盖CSS时也删除padding。

.test {
  width: 0;
  height: 0;
  padding:0;
}

.test {
  padding: 30px;
  width: 400px;
  height: 400px;
  box-sizing: border-box;
  background-color: orange;
  overflow: hidden;
}
 
 /* Setting width and height to zero. */
.test {
  width: 0;
  height: 0;
  padding:0;
}
<div class="test"></div>
<p>Have a div with padding of 30px and width and height of 100px. Box sizing is set to border box. When trying to set the width and height to zero, it does not work. Element stays at 60px X 60px dimensions. (Even with the overflow set to hidden).</p>
<p>Any idea what's going on here? Is there any way to make the width and height to zero including the paddings, so that it collapses completely?</p>


第二个规则将widthheight设置为0,因此它是60x60而不是460x460 - t.niese
这是关于宽度和高度的说明,它们各为400,包括填充后变为460。然后您只需删除宽度和高度,但保留四边30像素的填充即可。 - code.rider

0
你可以通过这样的“单次调用”来实现你想要的:
$('.test').css({ 'width': '0', height: '0', padding: '0' });

你的问题在于 padding 与 border-box 的结合。或者,你可以使用 display: none、visibility: hidden 或 opacity: 0。


用它来隐藏元素,以及在表单字段之间不留空隙 :) - mysiar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接