cross-fading elements with css transitions

you can't transition 'display', but don't let that stop you - the trick is visibility: hidden and transition delays

by jack gold

HTML

<div class="parent">
    <div class="child-1">yup</div>
    <div class="child-2">nope</div>
</div>
<small>⇧ click ⇧</small>

SCSS

.parent {
    width: 200px;
    height: 200px;
    background: #0cd;
    position: relative;
    cursor: pointer;
    transition: 0.5s background 0s;
}

.parent.active {
    background: #f82;
}


.parent .child-1 { 
    opacity: 1;
    visibility: visible;
    -moz-transition:0.5s opacity 0.25s, 0s visibility 0s;
    transition: 0.5s opacity 0.25s, 0s visibility 0s;
}

.parent .child-2,
.parent.active .child-1 {
    visibility: hidden;
    opacity: 0;
    -moz-transition: 0.5s opacity 0s, 0s visibility 0.5s;
    transition: 0.5s opacity 0s, 0s visibility 1s;
}

// these styles = the .parent .child-1 styles 
.parent.active .child-2 {
    opacity: 1;
    visibility: visible;
    -moz-transition: 0.5s opacity 0.25s, 0s visibility 0.25s;
    transition: 0.5s opacity 0.25s, 0s visibility 0.25s;
}



// mostly unnecessary demo stuff
.parent .child-1,
.parent .child-2 {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 0; right: 0; margin: auto;
    width: 100%;
    text-align: center;
    font-size: 30px;
    font-family: 'Avant Garde', Futura, sans-serif;
    text-transform: uppercase;
    color: white;
}

small {
    text-align: center;
    font-size: 12px;
    font-family: 'Avant Garde', Futura, sans-serif;
    text-transform: uppercase;
    width: 200px;
    margin-top: 10px;
    display: block;
    font-weight: bold;
}

JavaScript

$('.parent').on('click', function () {

    $(this).toggleClass('active');

});