Home > front end >  box-sizing: border-box and padding
box-sizing: border-box and padding

Time:09-25

Why is the border-sizing (border-box) not working on my div width padding? I want to animate the width of the div, starting from 0. But because of the padding the div never will be less than the padding I set.

What am I doing wrong here?

https://codepen.io/jnhltmn/pen/mdwGvMy

  box-sizing: border-box;
  color: #fff;
  background: #E2001A;
  position: absolute;
  margin: 85px;
  overflow: hidden;
  padding: 8px 10px;
  white-space: nowrap;
  width: 2px;

CodePudding user response:

<style>
.hotspotCaption1 {
  width: 300px;
  height: 100px;  
  padding: 50px;
  border: 1px solid red;
   box-sizing: border-box;
}

.hotspotCaption2 {
  width: 300px;
  height: 100px;  
  padding: 50px;
  border: 1px solid red;
}
</style>

<div class="hotspotCaption1">Consectetur Purus Fermentum Commodo</div><br>

<div class="hotspotCaption2">Consectetur Purus Fermentum Commodo</div>

your code is working properly but you have given very little width to the div which you can realize just give more width and create two different divs one with box-sizing and the other without box-sizing.

CodePudding user response:

Wrap your div inside another one and just animate the width of the parent div.

.hotspotCaption {
  font-size: 14px;
  box-sizing: border-box;
  color: #fff;
  background: #E2001A;
  padding: 8px 10px;
  white-space: nowrap;
}

.outer-wrp {
  margin: 85px;
  width: 2px;
  overflow: hidden;
}
<div class="outer-wrp">
  <div class="hotspotCaption">
    Consectetur Purus Fermentum Commodo
  </div>
</div>

CodePudding user response:

The most efficient solution that I have found and tested is this one:

.hotspotCaption {
  font-size: 14px;
  box-sizing: border-box;
  color: #fff;
  background: #E2001A;
  position: absolute;
  margin: 85px;
  overflow: hidden;
  padding: 0;
  white-space: nowrap;
  width: 0px;
  animation-duration: 1s; /* Change duration */
  animation-name: appear; /* Change its name */
  animation-iteration-count: 1; /* Change how many times it repeats */
  animation-direction: normal; /* Change its direction */
  animation-fill-mode: forwards; /* specifies a style when the animation stops */
}

@keyframes appear {
  from {
    padding: 0;
    width: 0;
  }
  to {
    padding: 8px 10px;
    width: 255px;
  }
}
<div class="hotspotCaption">Consectetur Purus Fermentum Commodo</div>

Also, here is a Pen I made: Link.

It did not work because box-sizing: border-box; does not affect padding in the way that you want, and there was no transition or animation applied in the first place. The thing is to make an animation that includes padding in its start position, and makes it zero. Hope this solution helped you!

  • Related