Skip to content Skip to sidebar Skip to footer

Reverse The Order Of Div's Children

How can you reverse the order of a div's children with pure CSS? For example: I want
A
B

Solution 1:

The modern answer is

#parent {
  display: flex;
  flex-direction: column-reverse;
}

Solution 2:

A little bit tricky, but can work; just to give you the idea:

div#top-to-bottom {
    position: absolute;
    width:50px;
    text-align: left;
    float: left;
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}
div#top-to-bottom > div {
    width: 50px;
    height: 50px;
    position: relative;
    float: right;
    display: block;
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}

mirror in the vertical axis both the container and the childs. The childs follow the inverted y axis of the container, but the children themselves are again head up.

demo

Solution 3:

<style>#parent{
    display: -webkit-flex; /* Safari */
    -webkit-flex-direction: row-reverse; /* Safari 6.1+ */display: flex;
    flex-direction: row-reverse;
}
</style>

Solution 4:

100% work this code:

<styletype="text/css">.wrapper {
       display: flex;
       flex-direction: column-reverse;
    }
</style><divclass="wrapper"><divclass="main">top</div><divclass="footer">bottom</div></div>

Solution 5:

CSS only solution: ( I switched all selectors to class selectors as to not deal with specificity issues that could occur. Just an habit of mine and others. I've also removed styles not relevant to the example. )

.top-to-bottom {
    position: absolute;
}

.child {
    width: 50px;
    height: 50px;
    margin-top: -100px; /* height * 2 */
}

.child:nth-child(1) {
    margin-top: 150px; /* height * ( num of childs -1 )  */
}

.a {
    background:blue;

}
.b {
    background:red;
}

.c {
    background:purple;
}

.d {
    background:green;
}

Demo:http://jsfiddle.net/zA4Ee/3/

Javascript solution:

var parent = document.getElementsByClassName('top-to-bottom')[0],
    divs = parent.children,
    i = divs.length - 1;

for (; i--;) {
    parent.appendChild(divs[i])
}

Demo:http://jsfiddle.net/t6q44/5/

Post a Comment for "Reverse The Order Of Div's Children"