简体   繁体   中英

Animating CSS by transitions when a class is added to an element

I'm using the Foundation framework on a project & it's Top Bar feature for navigation allows for drop-down navigation to appear on hover.

During the hover event it adds a .hover class to the relevant element, therefore the changes in CSS pop into sight rather than animating by way of a smooth transition.

This got me thinking. Is it possible to animate (via transitions or similar) the changes in CSS definitions?

Take this example. Here is our default element:

<div class="a-box">Some content</div>

And it's default CSS:

.a-box {
    width: 200px;
    height: 200px;
    background: red;
}

On hover the framework (which I do not wish to edit the core file to keep it clean for updates) adds the hover class. Making our element now look like this:

<div class="a-box hover">Some content</div>

Here could be some CSS for the hovered element:

.a-box.hover {
    width: 400px;

    // I thought perhaps adding the following would work but it doesn't appear to

    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    transition: all 200ms ease;
}

I'd be keen to hear others POV on this! I'm not sure if this is a duplicate, but all the posts I've read relate to some form of jQuery animation.

You aren't far off the mark, here is a working example .

The main error in your example is that you have

<div class="my-box hover">Some content</div>

But your CSS is looking for a-box not my-box .

As a habit, I normally define the animation on the simplest (most general) selector for the element and then any additional selectors will benefit from it.

.my-box {
    width: 200px;
    height: 200px;
    background: red;
    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    transition: all 200ms ease;
}

.my-box.hover {
    width: 400px;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM