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

时间:2015-12-11 09:46:33

标签: html css

有一个填充为30px,宽度和高度为100px的div。框大小设置为边框。尝试将宽度和高度设置为零时,它不起作用。元素保持在60px X 60px尺寸。 (即使将溢出设置为隐藏)。

知道这里发生了什么吗?有没有办法让宽度和高度为零,包括填充,以便它完全折叠?

.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>

3 个答案:

答案 0 :(得分:4)

根据CSS box model,边界内存在填充。因此这是正常行为。如果您只想在内容存在时显示padding,则可以使用:empty

删除内容为空的元素

&#13;
&#13;
.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;
}
&#13;
<div class="test"></div>
<div class="test">Test</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

填充还包括高度和宽度填充:30px表示从左,右,顶部和底部30px 它的意思是你的div实际大小是460X460所以你必须删除填充写入css

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

&#13;
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

通过“单一呼叫”实现您想要的目标:

$('.test').css({ 'width': '0', height: '0', padding: '0' });

你的问题是填充与边框一起使用。或者,您可以使用display:none,visibility:hidden或opacity:0