2014-09-22 45 views
1

我想在展開懸停在另一個元素上後保留div的寬度。這是我的代碼:使用懸停展開後保留div寬度(CSS)

CSS:

div.container{ 
width: 400px; 
height: 250px; 
border: 1px solid; 
clear: both; 

} 

.square{ 
width: 100px; 
height: 100px; 
background: black; 
float: left; 
position: relative; 
} 

.grow { 
width: 0px; 
height: 100px; 
float: left; 
background: black; 
position: relative; 
transition:width 0.5s; 
-webkit-transition:width 0.5s; 
background: green; 
} 

.square:hover + .grow { 
width: 200px; 
} 

而且還有我的html:

<div class="container"> 
     <div class="square"></div> 
     <div class="grow"></div> 
</div> 

我想唯一的CSS的解決方案。我知道這對JS很簡單,但我真的需要使用CSS。

非常感謝!

+0

我只是將它設置爲'position:absolute',這樣就不會考慮容器的佈局。 – MMM 2014-09-22 11:55:02

+0

當您沒有將鼠標懸停在'.square'上時,'.grow' div會恢復爲原始寬度。由於您試圖控制事件和行爲,因此您需要使用JavaScript/jQuery。 CSS是用於造型的。 – 2014-09-22 12:10:00

回答

3

設置一個收縮動畫部分的過渡時間非常高,這會產生不縮小的效果。沒有js的要求,只是將它設置爲像3600s(也許嘗試更高?),這將是一個小時將給你一個長時間的視覺靜態。我找不到最長的時間,但它似乎工作。

div.container{ 
 
    width: 400px; 
 
    height: 250px; 
 
    border: 1px solid; 
 
    clear: both; 
 
} 
 

 
.square{ 
 
    width: 100px; 
 
    height: 100px; 
 
    background: black; 
 
    float: left; 
 
    position: relative; 
 
    transition:width 5s; 
 
    -webkit-transition:width 5s; 
 
} 
 

 
.grow { 
 
    width: 0px; 
 
    height: 100px; 
 
    float: left; 
 
    background: black; 
 
    position: relative; 
 
    transition:width 3600s; 
 
    -webkit-transition:width 3600s; 
 
    background: green; 
 
} 
 

 
.square:hover + .grow{ 
 
    width: 200px; 
 
    transition:width 0.5s; 
 
    -webkit-transition:width 0.5s; 
 
}
<div class="container"> 
 
     <div class="square"></div> 
 
     <div class="grow"></div> 
 
</div>

+0

好戲。 Upvoted在盒子外面思考。 – easwee 2014-09-22 12:08:49

+0

感謝@easwee前段時間遇到同樣的問題,結束了使用jquery,但這會做伎倆 – 2014-09-22 12:10:19

+0

非常感謝!這樣一個好人把戲! – Katalhama 2014-09-23 09:04:04

2

使用動畫(而非過渡)是一個選項:

.container { 
 
    width: 400px; 
 
    height: 250px; 
 
    border: 1px solid; 
 
} 
 

 
.square { 
 
    width: 100px; 
 
    height: 100px; 
 
    background: black; 
 
    float: left; 
 
    position: relative; 
 
} 
 

 
.grow { 
 
    width: 0; 
 
    height: 100px; 
 
    float: left; 
 
    background: black; 
 
    position: relative; 
 
    transition: width 0.5s; 
 
    background: green; 
 
    animation-fill-mode: both; 
 
    animation-name: extend; 
 
    animation-duration: 1000ms; 
 
    animation-play-state: paused; 
 
} 
 

 
.square:hover + .grow { 
 
    animation-play-state: running;  
 
} 
 

 
@keyframes extend { 
 
    0% { width: 0; } 
 
    100% { width: 200px; } 
 
}
<div class="container"> 
 
     <div class="square"></div> 
 
     <div class="grow"></div> 
 
</div>

Lea Verou的文章是一個很好看的:基本上我們「在之間重新切換animation-play-state 210和running,並使用animation-fill-mode確保展開的div保留了我們想要的樣式,一旦動畫完成。有一個小提琴here

這裏的缺點是,如果您懸停.square,但在動畫完成前將光標關閉,那麼.grow. div會半途被卡住(這可能是也可能不是問題,並且可能會成爲問題與任何只有CSS的解決方案)。