簡體   English   中英

CSS Flexbox:更改另一個Flex項目的位置時,Flex項目會增加

[英]CSS Flexbox: flex item grow when changing another flex items position

在下面的示例中,我有3個flex項目。 我想做的是,當我改變藍色的位置時,讓綠色的位置增長。 我找不到在CSS中執行此操作的方法,還是應該在JS中手動編寫。

 $(document).ready(function(){ $("#btnStart").click(function(){ $("#three").addClass("slide-right"); }); }); 
 main { display: flex; flex-flow: row no-wrap; width: 100%; height: 500px; justify-content: flex-start; overflow: hidden; } div { position: relative; } #one { width: 200px; background-color: red; } #two { flex: 1; background-color: green; } #three { width: 200px; background-color: blue; left: 0; transition: left 400ms; } #three.slide-right { left: 200px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <input type="button" id="btnStart" value="Start" /> <main> <div id="one"></div> <div id="two"></div> <div id="three"></div> </main> 

因為div的位置是relative所以left屬性不會更改布局。

根據MDN關於位置的文章

相對的

該關鍵字對所有元素進行布局,就像未放置元素一樣,然后在不更改布局的情況下調整元素的位置(因此,如果沒有放置元素,則在元素上會留有空隙)。 position:相對於table-*-group,table-row,table-column,table-cell和table-caption元素的影響是不確定的。


如果您不希望更改元素本身的寬度,則不要滑動它。 您可以將其包裝在容器中,然后更改容器的寬度(請參見代碼段)。

 $(document).ready(function() { $("#btnStart").click(function() { $("#threeContainer").addClass("slide-right"); }); }); 
 main { display: flex; flex-flow: row no-wrap; width: 100%; height: 500px; justify-content: flex-start; overflow: hidden; } #one { width: 200px; background-color: red; } #two { flex: 1; background-color: green; } #threeContainer { width: 200px; transition: width 400ms; } #threeContainer.slide-right { width: 0; } #three { height: 100%; width: 200px; background-color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <input type="button" id="btnStart" value="Start" /> <main> <div id="one"></div> <div id="two"></div> <div id="threeContainer"> <div id="three"> I'm an example text that won't change when #three slides </div> </div> </main> 

由於元素僅在屏幕上移動,因此它使用的初始空間不可用。

您可以使用負邊距釋放一些空間,就像拉動綠色元素一樣。

 $(document).ready(function(){ $("#btnStart").click(function(){ $("#three").addClass("slide-right"); }); }); 
 main { display: flex; flex-flow: row no-wrap; width: 100%; height: 500px; justify-content: flex-start; overflow: hidden; } div { position: relative; } #one { width: 200px; background-color: red; } #two { flex: 1; background-color: green; } #three { width: 200px; background-color: blue; left: 0; transition: left 400ms; } #three.slide-right { left: 200px; margin-left:-200px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <input type="button" id="btnStart" value="Start" /> <main> <div id="one"></div> <div id="two"></div> <div id="three"></div> </main> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM