Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Setting element's width and height to zero

Tags:

html

css

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

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?

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

2 Answers

According the CSS box model, padding is present within the border. Thus this is normal behavior. If you want to show padding only when the content is present, you can remove the element if the content is empty using :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>
like image 172
m4n0 Avatar answered Sep 18 '25 08:09

m4n0


padding is also include in height and width padding:30px mean 30px from left,right,top and also from bottom its mean your div actual size is 460X460 so you have to remove padding also in 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>
like image 36
code.rider Avatar answered Sep 18 '25 08:09

code.rider