0

How can I do this

<div>
  <p>A</p>
  <p>B</p>
  <p>C</p>
</div>

What I expected to be the results

C

B

A

How can I achieve this?

Jayvee Embog
  • 47
  • 2
  • 6
  • You can use flex box. set `flex-direction: column-reverse;` – Rinkesh Golwala Sep 15 '20 at 13:54
  • CSS Dupe: [How can I reorder my divs using only CSS?](https://stackoverflow.com/questions/220273/how-can-i-reorder-my-divs-using-only-css); A possible JavaScript Dupe: [Reverse order of a set of HTML elements](https://stackoverflow.com/questions/7942733/reverse-order-of-a-set-of-html-elements) – Andreas Sep 15 '20 at 13:59
  • You can also use transform: `div, p { transform:scale(-1); }` result live : https://jsfiddle.net/hy709jv8/ – G-Cyrillus Sep 15 '20 at 14:14

2 Answers2

1

Using CSS

You can order the items in reverse, by specifying flex display.

div {
  display: flex;
  flex-direction: column-reverse;
}
<div>
  <p>A</p>
  <p>B</p>
  <p>C</p>
</div>

Alternatively, you could transform the child elements by flipping them across their directional axis. Flip the entire div and then flip each p inside the div. Although this works, it should be avoided in favor of flex. Note: After transforming the elements, selection will become very wonky.

div, p {
  transform: scale(1, -1);
}
<div>
  <p>A</p>
  <p>B</p>
  <p>C</p>
</div>

Using JavaScript

You could also do this in JavaScript using a function that iterates though a Node's childNodes and inserts them before the first child.

/**
 * @describe Reverses the child nodes of a node in-place.
 * @param {Node} node - The parent of the child nodes to be reversed
 */
const reverseChildNodes = node => {
  for (let i = 1; i < node.childNodes.length; i++) {
    node.insertBefore(node.childNodes[i], node.firstChild);
  }
}

if (Element.prototype.reverseChildren === undefined) {
  Element.prototype.reverseChildren = function() {
    reverseChildNodes(this);
  };
}

// Global function
reverseChildNodes(document.querySelector('.section:first-child'));

// Prototype method on Node object
[...document.querySelectorAll('.section')].pop().reverseChildren();
.section { border: thin solid grey; margin: 0.25em; padding: 0.25em; }
<div class="section">
  <p>A</p>
  <p>B</p>
  <p>C</p>
</div>

<div class="section">
  <p>A</p>
  <p>B</p>
  <p>C</p>
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1
Use flexbox :

.wrapper{
display :flex;
flex-direction: column-reverse;
}
<div class='wrapper'>
  <p>A</p>
  <p>B</p>
  <p>C</p>
</div>