0

This question is similar to this question resolved previously: CSS text-align delay with width animation

I have an animation that goes from 0% width to 100% with the intent of loading the page without any text visible and immediately revealing it from left to right.

I noticed that with the padding included, the first portion of the text on the left loads already visible. What is the reason for this? Thanks!

@keyframes leftright {
      0% {
        max-width: 0%;
      }
      100% {
        max-width: 100%;
      }
    }

    .test_1 {
      overflow: hidden;
      white-space: nowrap;
      width: 80vw;
      padding: 0 10vw;
      border: 1px solid red;
      font: bold 15vmin 'Playfair Display', serif;
      animation: leftright 1s;
    }
 <div class="test_1">Why hello there</div>
    
J Lou
  • 45
  • 5

2 Answers2

2

That's because the CSS width property (and also max-width and min-width properties) refer to the content width. The content is what's inside the margin, border and padding in the box model.

If you look at the starting property of your div.test_1, they are:

.test_1 {
   overflow: hidden;
   white-space: nowrap;
   padding: 0 10vw;  
   max-width: 0;
   border: 1px solid red;
   font: bold 15vmin 'Playfair Display', serif;
}
<div class="test_1">Why hello there</div>

The visual width of the element is actually due to the width plus the left and right padding values of 10vw, plus the left and right border widths.

To work around it, you could do what JasonB suggested.

Alternatively, you could include the padding in your keyframes, which has the side-effect of animating the (left and right) padding also.

@keyframes leftright {
  0% {
    padding: 0;
    max-width: 0;
  }
  100% {
    padding: 0 10vw;
    max-width: 100%;
  }
}

.test_1 {
  overflow: hidden;
  white-space: nowrap;
  /* width: 80vw;  <-- I removed this as it appears to contradict with max-width */
  border: 1px solid red;
  font: bold 15vmin 'Playfair Display', serif;
  max-width: 100%;
  padding: 0 10vw;
  animation: leftright 1s;
}
<div class="test_1">Why hello there</div>
Frank Fajardo
  • 7,034
  • 1
  • 29
  • 47
1

You can achieve the desired behavior without the unwanted side effects by splitting up the presentation and animation jobs and assigning them to separate divs.

Here is another question that has an answer to explain why the padded div doesn't have a width of zero. border-box with padding can't have 0 width

@keyframes leftright {
  0% {
    max-width: 0%;
  }
  100% {
    max-width: 100%;
  }
}

.test_1 {
  animation: leftright 10s;
  overflow: hidden;
  white-space: nowrap;
  width: 80vw;
  border: 1px solid red;
}

.test_2 {
  padding: 0 10vw;
  font: bold 15vmin 'Playfair Display', serif;
}
<div class="test_1">
  <div class="test_2">Why hello there</div>
</div>
JasonB
  • 6,243
  • 2
  • 17
  • 27