#Sliding divs strange behaviour

1 messages · Page 1 of 1 (latest)

elfin lantern
#

I have an angular component where the idea is it has one container div, with two child box divs. Both child divs inherit the full width of the parent. But only one child is visible on-screen at once. When the "next()" method is called, the children divs slide across using the "left" property, to switch between which is visible.
Here is some simplified code for how I'm doing it:

<div class="add-partner-container">
  <div class="box" [style.left]="sliderIndex === 0 ? '0' : '-100%'"> 
    <p>First Box</p>
  </div>
  
  <div class="box" [style.left]="sliderIndex === 1 ? '0' : '100%'">
    <p>Second Box</p>
  </div>
</div>
.add-partner-container {
  width: 100%;
  height: 11rem;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  position: relative;
}

.box {
  width: 100%;
  position: absolute;
  transition: left 0.5s ease-in-out;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow-y: hidden;
}

  public sliderIndex: number = 0;

  public next() {
    this.sliderIndex = (this.sliderIndex + 1) % 2;
  }

I have this problem:
When I first open the angular component in the browser, it initially correctly shows the first box, as it should. But it suddenly switches to showing the second box, which it should not show until the "next()" method is called, which it has not been yet.

The next() method is not accidentally being called. The sliderIndex field is not being modified by any other part of the code.
I've confirmed all of this.

#

When I inspect the elements, I can confirm that the "left" property is set correctly. This indicates that the "sliderIndex" value is at the correct value.

The problem is that when the first box has a confirmed "left" property value of 0% and the second box has a confirmed "left" property value of 100%, the first box should be visible. But in reality, the second box is visible.

eager yarrow
#

You should provide a minimal stackblitz reproduction to get better help.
At frst sight, I think you're quite shooting yourself in the foot using absolute positioning on flex items.
Probably what you want to get is easily achievable through transformX().

elfin lantern
#

I didn't know using absolute positioning with flex was problematic?
I've used it in the past without much issue 🤔

But I'll try out your suggestion with transformX and without flex/absolute, thanks 🙂

eager yarrow
#

It's not a rule, but personally I'm not a great fan of absolute positioning in general.

elfin lantern
eager yarrow
#

Nothing really objective.
Mainly personal taste, because absolute positioned elements may be tricky to manage in responsive design.
If you provide a repro of your issue, we can try to fix it keeping absolute position, tho.