Home > OS >  Fix Flex Box Size Regardless of it's innerText
Fix Flex Box Size Regardless of it's innerText

Time:01-04

How can I fix div's size? (I mean .long div on this codes)

Actually div's size is fixed. but, div's inner text is changing its width.

So, Position of Floating Point of my content is Changing.

I think cause of this problem is flex-end.

than, What is Best way of this problem with notating content on end of div?

enter image description here

.parent{
    width: 400px;
    height: 200px;
    display: flex;
}

.long{
    width: 80%;
    height: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.short{
    width: 20%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
<div >
    <div >
       {dynamicNumberNotate}
    </div>
    <div >
        foo
    </div>
</div>

CodePudding user response:

Your div .long has a width of 80% of its parent, which is not a fixed width. There are three possible solutions:

  • Give it a fixed width (e.g. 400px)
  • Use the word-break css property to break the number apart when it's too long
  • Make sure that there's enough space for the number to fit.

Additionally, the display property is a bit tricky and can have unexpected effects. Perhaps you can achieve a better result changing something in conjuction with a different display value for the child divs.

CodePudding user response:

So to ensure your decimal point doesn't move as the text moves, you have to split your div in to two sub elements. Ensure the 2nd has enough width to cope with 2 characters. There's a really handy css unit called ch for this.

window.onload = () => {
  setInterval(() => {
    const numString = (Math.random() * 3000).toFixed(2);
    document.querySelector('.long').textContent = numString.split('.')[0]   ".";
    document.querySelector('.short').textContent = numString.split('.')[1];
  }, 500);
}
.parent {
  width: 400px;
  height: 200px;
  display: flex;
}

.long {
  width: 80%;
  height: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-right: 1px solid red;
  background-color: goldenrod;
}

.short {
  width: 2ch;
  height: 100%;
  display: flex;
  justify-content: left;
  align-items: center;
  background-color: lightskyblue;
}
<div >
  <div ></div>
  <div ></div>
</div>

  • Related