简体   繁体   中英

Retain element screen position after adding a new element before it in DOM

I have a div containing two spans which hold text:

<div class="jumbotron">
    <span id="span-one" class="name-letters">One</span>
    <span id="span-two" class="name-letters">Two</span>
</div>

I perform a CSS animation on these spans to move one element away from the other (took out browser prefixes for better legibility) JSFiddle :

#span-two {
    animation-delay: 3s;
    animation-duration: 3s;
    animation-name: slide;
    animation-fill-mode: forwards;
}

@keyframes slide {
    from {
        margin-left: 0%;
    }
    to {
        margin-left: 25%;
    }
}

Example:

start:

One Two

stop:

One          Two

Now, I would like to add a third span, once the animation has completed, next to the first span. However, I would like the second span to keep its animation end position.

Example:

what I want:

One Three    Two

what I get: JSFiddle

One Three          Two

This is because I add to the margin-left attribute of the second span for it to move in the animation. So, when I add a new element before it, the second span moves further to meet the margin-left value that was set. My Question: How can I achieve this without moving the second spans position after the third span is added?

You can set span #3 positioned absolutely (or fixed ), but without specifying top and left values (!):

#span-three {
    position: absolute;
}

and

span.id = "span-three";

Demo: http://jsfiddle.net/gcgtveo5/2/

I can't write pure javascript, but could you do something like this instead of the absolute positioned span?

HTML:

<div>
    <div class="container">
    <span id="span-one" class="name-letters">One</span>
    </div>
    <div class="container" id="spanThreeContainer">
    </div>
    <div class="container">
    <span id="span-two" class="name-letters">Two</span>
    </div>

CSS:

.container {width:33.33%; float:left;}

and then append your new span to '#spanThreeContainer'?

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