Search code examples
htmlcssflexboxreact-transition-group

CSS transition width not working with flex


Layout:

<div style={{ flex:1 }}>
    <div className="sideBarContainer">
         <div className="sideBar">
         <div className="sideBarExtra"> <--- conditional
    </div>
    <div className="content"></div>
</div>

CSS:

.sideBarContainer {
    display: flex;
    flex-direction: row;
}
.sideBar {
    height: 100vh;
    min-width: 64px;
    z-index: 99;
}
.content {
    flex: 1;
    transition: width .3s linear;
}

sideBarExtra conditionally renders using the react-tranisition-group CSSTransitionGroup component.

The sideBarExtra will slide in smoothly from left to right when it is rendered, and slide out right to left when it is removed.

The content div does not transition smoothly when sideBarExtra is added, it jumps to its spots.

Expected behaviour: content to smoothly slide to it's new width.

In the console dev tools I can see the content width being changed, but no transition animation is happening.


Solution

  • .sideBarContainer {
        display: flex;
        flex-direction: row;
        width: 100%;
    }
    .sideBar {
        background: red;
        height: 100vh;
        min-width: 64px;
        z-index: 99;
    }
    
    .content {
        width: 10%;
        height: 100vh;
        background: yellow;
        transition: width .3s linear;
    }
    .content:hover {
      width: 80%;
    }
    <div style="display:flex;">
        <div class="sideBarContainer">
             <div class="sideBar">
             <div class="sideBarExtra"> </div>
        </div>
        <div class="content">Hover me</div>
    </div>

    You can change the instant

    .content {
        flex: 1;
        transition: width: .3s linear;
    }
    

    to

    .content {
        flex: 1;
        transition: width .3s linear;
    }
    

    the transition does not take any : Colon here the above code

    Answer 2

    You can also set animation for flex property here the example:

    .sideBarContainer {
        display: flex;
        flex-direction: row;
        width: 100%;
    }
    .sideBar {
        background: red;
        height: 100vh;
        min-width: 64px;
        z-index: 99;
        flex: 2;
        transition: flex .3s linear;
    }
    
    .content {
        flex: 1;
        height: 100vh;
        background: yellow;
        transition: flex .3s linear;
    }
    .sideBarContainer:hover .sideBar { 
      flex: 1;
    }
    .sideBarContainer:hover .content {
      flex: 2 0 auto;
    }
    <div style="display:flex;">
        <div class="sideBarContainer">
             <div class="sideBar">
             <div class="sideBarExtra"> </div>
        </div>
        <div class="content">Hover me</div>
    </div>