skyisred
skyisred

Reputation: 7105

Transition to and from position Auto

An element is arbitrarily placed on a page, and needs to transition to a fixed position on event (screen scroll in my case, but im using hover in the fiddle)

The original position of the element is centered withing a parent (top: auto and left: auto). On hover, it's supposed to smoothly move to the corner of the screen (left: 0, top: 0) and then comeback. Instead, it just jumps in place, ignoring the transition property.

I realize that none of the browsers support transition to auto, but was hoping to find some work around for this.

fiddle

<div>
    <span>test</span>
</div>

div {
    border: 1px solid red;
    text-align: center;
    height: 100px;
    margin: 15px;
}
span {
    display: inline-block;
    width: 50px;
    height: 50px;
    background: blue;
    transition: all 1s;
    position: fixed;
    left: auto;
    top: auto;
}
div:hover span {
    left: 0;
    top: 0;
}

PS. I'm hoping for a css only fix, but a solution with JQuery would work as well.

Upvotes: 8

Views: 1665

Answers (2)

Yandy_Viera
Yandy_Viera

Reputation: 4380

Why don't you set a specific top and left? you have span{position: fixed} so in this case you always know about your top, right, bottom, left (relative to viewport).

so try with:

div {
    border: 1px solid red;
    text-align: center;
    height: 100px;
    margin: 15px;
}
span {
    display: inline-block;
    width: 50px;
    height: 50px;
    background: blue;
    transition: all 1s;
    position: fixed;
    left: 50%;
    margin-left: -25px; /*or transform: translateX(-50%) if you don't know the width of span*/
    top: 16px;
}
div:hover span {
    left: 0;
    top: 0;
    margin-left: 0; /*or transform: none if you don't know the width of span*/
}
<div>
    <span>test</span>
</div>

You can change the top left as you which to achieve what you want.

Here a jsfiddle example to play with

Upvotes: 0

Matthew Beckman
Matthew Beckman

Reputation: 1722

You are correct in that modern browsers are unable to transition to 'auto'. You can use CSS to achieve what you're looking for though.

In your example, you'll need to center by changing

top: auto;
left: auto;

to

vertical-align: top;
left: calc(50% - 25px);

Remove the top property from the span and span:hover and replace it with vertical-align.

JSFiddle Example

Upvotes: 1

Related Questions