Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

css - Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

http://jsfiddle.net/nicktheandroid/tVHYg/

When hovering .wrapper, it's child element .contents should animate from 0px to it's natural width. Then when the mouse is removed from .wrapper, it should animate back down to 0px. The .wrapper element should only be as wide as it needs to be (allowing .contents to grow), so .wrapper should grow in width and shrink in width as .contents does. There should be no set width for .contents. I'm using CSS3, but it could be accomplished in jQuery, that would be fine.

The problem: See the JSfiddle

  1. .wrapper is not only as wide as it needs to be.
  2. when .contents grows, when it's almost at it's full width, it jumps down to the next line
  3. When hovering off of .wrapper, .contents vanishes, when it should animate down to 0px

.wrapper {
    display: inline-block;

    height: 20px;
    width: auto;
  
    padding:10px;
  
    background:#DDD;
}

.contents {
    display:inline-block;
  
    width:0%;
  
    white-space:nowrap;
    overflow:hidden;
  
    background:#c3c;
}

.wrapper:hover .contents {
    -webkit-transition: width 1s ease-in-out;
    -moz-transition: width 1s ease-in-out;
    -o-transition: width 1s ease-in-out;
    transition: width 1s ease-in-out;

    width:100%;
}
<div class="wrapper">
    <span>+</span>
    <div class="contents">These are the contents of this div</div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think I've got it.

.wrapper {
    background:#DDD;
    display:inline-block;
    padding: 10px;
    height: 20px;
    width:auto;
}

.label {
    display: inline-block;
    width: 1em;
}

.contents, .contents .inner {
    display:inline-block;
}

.contents {
    white-space:nowrap;
    margin-left: -1em;
    padding-left: 1em;
}

.contents .inner {
    background:#c3c;
    width:0%;
    overflow:hidden;
    -webkit-transition: width 1s ease-in-out;
    -moz-transition: width 1s ease-in-out;
    -o-transition: width 1s ease-in-out;
    transition: width 1s ease-in-out;
}



.wrapper:hover .contents .inner {
   
    width:100%;
}
<div class="wrapper">
    <span class="label">+</span><div class="contents">
        <div class="inner">
            These are the contents of this div
        </div>
    </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...