Home > OS >  Why are my flexbox items misaligned when the parent width changes?
Why are my flexbox items misaligned when the parent width changes?

Time:04-03

I've got a problem with flexbox.
What I want to do is this:

screenshot

I almost did it.
However, for an unknown reason (for me), if the width (of the div or browser) is to small, it's not aligned anymore. The problem seems to be because of the multiple lorem ipsum, but I can't understand why.

enter image description here

.timeline {
  display: flex;
}

.timeline>div {
  display: flex;
  flex-grow: 1;
  border: 1px solid red;
}

.events {
  width: 50%;
}

.date,
.relative,
.events {
  border: 1px solid green;
}

.date,
.relative {
  width: 80px;
}
<!DOCTYPE html>
<html lang="fr">

<head></head>

<body>
  <div >
    <p >a1</p>
    <p >a2</p>
    <div>
      <div ></div>
      <div ></div>
    </div>
  </div>

  <div >
    <p >b1</p>
    <p >b2</p>
    <div>
      <div >
        <p>Lorem ipsum</p>
      </div>
      <div >
        <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ium Lorem ipsum Lorem ipsum Lorem ipsum</p>
      </div>
    </div>
  </div>
</body>

</html>

Do you have any idea what's going on? Thanks a lot.

CodePudding user response:

Use flex: 1; instead of flex-grow: 1;.

flex: 1; is a shorthand for:

flex-grow: 1; = Element will grow in same proportion as the window-size

flex-shrink: 1; = Element will shrink in same proportion as the window-size

flex-basis: 0; = Element does not have a starting value as such and will take up screen as per the screen size available for e.g:- if 3 divs are in the wrapper then each div will take 33%.

Source for above: https://stackoverflow.com/a/37386525/14776809

.timeline {
  display: flex;
}

.timeline>div {
  display: flex;
  border: 1px solid red;
  flex: 1;
}

.events {
  width: 50%;
}

.date,
.relative,
.events {
  border: 1px solid green;
}

.date,
.relative {
  width: 80px;
}
<!DOCTYPE html>
<html lang="fr">

<head></head>

<body>
  <div >
    <p >a1</p>
    <p >a2</p>
    <div>
      <div ></div>
      <div ></div>
    </div>
  </div>

  <div >
    <p >b1</p>
    <p >b2</p>
    <div>
      <div >
        <p>Lorem ipsum</p>
      </div>
      <div >
        <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ium Lorem ipsum Lorem ipsum Lorem ipsum</p>
      </div>
    </div>
  </div>
</body>

</html>

  • Related