【问题标题】:CSS - Setting element's width and height to zeroCSS - 将元素的宽度和高度设置为零
【发布时间】:2016-03-17 04:23:11
【问题描述】:

有一个内边距为 30 像素、宽度和高度为 100 像素的 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>

【问题讨论】:

  • 移除填充 - 填充在宽度中
  • 根据 CSS 框模型,填充存在于边框内。因此这是正常行为。
  • 如果您不想应用padding,为什么还要添加padding
  • 如果你想隐藏为什么不能使用display:none?你能告诉我你需要这个的场景吗?
  • 有没有办法用一个电话来完成?比如 $('.test').css('width': '0'); ?

标签: html css


【解决方案1】:

根据CSS box model,边框内存在填充。因此,这是正常行为。如果您只想在内容存在时显示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>

【讨论】:

    【解决方案2】:

    填充也包括在高度和宽度填充中:30px 表示从左、右、顶部和底部的 30px 这意味着您的 div 实际大小为 460X460,因此您还必须在 over write css 中删除填充

    .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
    • 这只是为了解释你的宽度和高度是 400,包括填充它变成 460,然后你只删除宽度和高度,但从 4 个边保留 30px 的填充
    【解决方案3】:

    您可以通过这样的“一次调用”实现您想要的:

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

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

    【讨论】:

    • 将它用于不同的目的:隐藏元素并且在表单字段之间没有间隙:)
    猜你喜欢
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多