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

Time:04-02

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 >
  <div >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?

CodePudding user response:

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 >
  <div >Loading</div>
</div>

CodePudding user response:

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 >
  <div >Loading</div>
</div>

CodePudding user response:

why not just add a width:100px to .loading?

.container {
  display: flex;
}

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

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

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

  • Related