Ryan Peschel
Ryan Peschel

Reputation: 11848

How to make a div always be the largest size it could be and not dynamically resize?

I have the following code:

.container {
  display: flex;
}

@keyframes dotty {
  0%   { content: ''; }
  25%  { content: '.'; }
  50%  { content: '..'; }
  75%  { content: '...'; }
  100% { content: ''; }
}

.loading {
  display: flex;
  padding: 8px;
  background-color: #ddd;
}

.loading::after {
  display: inline-block;
  animation: dotty steps(1, end) 1s infinite;
  content: '';
}
<div class="container">
  <div class="loading">Loading</div>
</div>

As you can see, the element increases and decreases in size based on the amount of dots showing.

I want it to always be the same size.

The size I want it to be is the largest size that it can possibly be (that would be when it's filled with Loading... text).

I could solve this by setting the width property, but I don't know what the width is, and I don't want to hardcode a value.

Is it possible to size the element based a child which it doesn't have? The only solution I could think of is to create a visibility: hidden child with the Loading... text in it, but that seems a bit hackish. Also, that solution adds an extra line to the top of it, so it doesn't even work that well either.

Is there a better way?

Upvotes: 0

Views: 67

Answers (2)

Temani Afif
Temani Afif

Reputation: 274175

use white-space: pre; and add spaces instead of dots to have the content always the same

.container {
  display: flex;
}

@keyframes dotty {
  0%   { content: '   '; }
  25%  { content: '.  '; }
  50%  { content: '.. '; }
  75%  { content: '...'; }
  100% { content: '   '; }
}

.loading {
  display: flex;
  padding: 8px 0px 8px 8px;
  background-color: #ddd;
  width: 10ch;
}

.loading::after {
  display: inline-block;
  animation: dotty steps(1, end) 1s infinite;
  white-space: pre;
  content: '';
}
<div class="container">
  <div class="loading">Loading</div>
</div>

Upvotes: 1

corn_not_supported
corn_not_supported

Reputation: 1

Edited solution after comments:

.container {
  display: flex;
}

@keyframes dotty {
  0%   { content: ''; }
  25%  { content: '.'; }
  50%  { content: '..'; }
  75%  { content: '...'; }
  100% { content: ''; }
}

.loading {
  display: flex;
  padding: 8px 0px 8px 8px;
  background-color: #ddd;
  width: 10ch;
}

.loading::after {
  display: inline-block;
  animation: dotty steps(1, end) 1s infinite;
  content: '';
}
<div class="container">
  <div class="loading">Loading</div>
</div>

Upvotes: 0

Related Questions