2017-08-07 56 views
0

當我縮小窗口時,是否可以「重新排列」我的div-blocks? 例如,如果紅色div出現在藍色div之前,當我縮小到0-770px寬度的窗口。但是當窗戶最小時。 771px,藍色div應該出現在紅色div之前。縮放時重新排列div

林不知道這是可能的,但沒有javascript的解決方案是deffintly更可取。

謝謝!

@charset "utf-8"; 
 

 
/* CSS Document */ 
 

 
#wrapper { 
 
    width: 1000px; 
 
    height: auto; 
 
    background-color: grey; 
 
} 
 

 
#boks-green { 
 
    width: 50%; 
 
    background-color: green; 
 
    height: 400px; 
 
    display: block; 
 
    float: left; 
 
} 
 

 
#boks-blue { 
 
    width: 50%; 
 
    background-color: deepskyblue; 
 
    height: 400px; 
 
    display: block; 
 
    position: relative; 
 
    float: left; 
 
} 
 

 
#boks-red { 
 
    width: 50%; 
 
    background-color: red; 
 
    height: 400px; 
 
    display: block; 
 
    position: relative; 
 
    float: left; 
 
} 
 

 
#boks-purple { 
 
    width: 50%; 
 
    background-color: purple; 
 
    height: 400px; 
 
    display: block; 
 
    position: relative; 
 
    float: left; 
 
} 
 

 
@media only screen and (max-width: 770px) { 
 
    #boks-green { 
 
    width: 100%; 
 
    background-color: green; 
 
    height: 400px; 
 
    display: block; 
 
    float: left; 
 
    } 
 
    #boks-blue { 
 
    width: 100%; 
 
    background-color: deepskyblue; 
 
    height: 400px; 
 
    display: block; 
 
    position: relative; 
 
    float: left; 
 
    } 
 
    #boks-red { 
 
    width: 100%; 
 
    background-color: red; 
 
    height: 400px; 
 
    display: block; 
 
    position: relative; 
 
    float: left; 
 
    } 
 
    #boks-purple { 
 
    width: 100%; 
 
    background-color: purple; 
 
    height: 400px; 
 
    display: block; 
 
    position: relative; 
 
    float: left; 
 
    } 
 
}
<div id="wrapper"> 
 
    <div id="boks-green"> 
 
    </div> 
 

 
    <div id="boks-blue"> 
 
    </div> 
 

 
    <div id="boks-red"> 
 
    </div> 
 

 
    <div id="boks-purple"> 
 
    </div> 
 

 
</div>

+0

這可以通過[flexbox and order](https://css-tricks.com/snippets/css/a-guide-to-flexbox/#article-header-id-9)來實現。 – jrenk

+0

可能有[只用CSS交換DIV位置]的副本(https://stackoverflow.com/questions/17455811/swap-div-position-with-css-only) – rblarsen

+1

有浮動和已知高度,可以玩塊格式化上下文和交換紅色和藍色框https://codepen.io/anon/pen/dzNBdL清除和溢出 –

回答

2

如果你可以考慮使用flexbox,這是時下quite well supported,你可以很容易地做到這一點。

首先,您需要媒體查詢,然後如果您的容器是容器flex,則可以使用兒童的order屬性來選擇要顯示元素的位置。

所以我會用:

#boks-blue { 
order: 1; 
} 

#wrapper { 
    display: flex; 
    flex-direction: column; 
} 

媒體查詢內。

您可以瞭解更多關於彈性盒here或者您可以以非常互動的方式深入挖掘here

+0

但是,當包裝是「顯示器:彎曲」我的div不相互下,但對齊水平 –

+1

您可以更改這與包裝的'flex-direction'有關。 它可以使用'row'(默認),'column','row-reverse'和'column-reverse'值。 所以你應該把它放在'flex-direction:column'上。 我在主要答案上添加了一些文檔。 – MisterJ

+0

@AdrianKirkegaard如果這個解決方案解決了你的問題,你應該接受它。 – MisterJ