How to change the order of elements without changing the html code?

  • A+
Category:Languages

These are 3 inline-block and elements which means that they will be ordered next to each other.

Here is a fiddle to view everything live: https://jsfiddle.net/8mdm8eox/

.wrapper {   background: #fff;   width: 100% }  .firstElement, .secondElement, .thirdElement {   display: inline-block;   width: calc(100%/3) }  .firstElement {   background: #000;   color: #fff }  .secondElement {   background: grey }  .thirdElement {   background: #ddd }  @media (max-width: 767px) {}
<div class="wrapper">   <div class="firstElement">First Element</div>   <div class="secondElement">Second Element</div>   <div class="thirdElement">Third Element</div> </div>

So here is what I want , I want when the screen width is 767px or less:

@media (max-width: 767px){} 

The first two elements are ordered vertically and the third one is ordered horizontally with the two other elements, So that they become like:

   _______________    ________________    |First Element|    |ٍ              |    _______________    |              |                         |Third Element |    ________________   |              |    |Second Element|   |              |    _________________  _______________ 

Don't worry about the third element , The text will be broken , I just want the first two elements to look like that without changing the html.


There are various ways to re-order your elements without altering the HTML.

CSS flexbox provides the order property. However, flex may not be a good option for you since you want one element to span two rows. The problems you may encounter are discussed here:

CSS grid layout, however, offers many good solutions to your problem. The order property is also available here, but it's not necessary.

Here's one solution using the grid-template-areas property.

.wrapper {   display: grid;   grid-gap: 5px;   grid-template-areas: "first second third"; }  .firstElement {   grid-area: first;   background: #000;   color: #fff }  .secondElement {   grid-area: second;   background: grey }  .thirdElement {   grid-area: third;   background: #ddd }  @media (max-width: 767px) {   .wrapper {     grid-template-areas: "first third"                           "second third";   }
<div class="wrapper">   <div class="firstElement">First Element</div>   <div class="secondElement">Second Element</div>   <div class="thirdElement">Third Element</div> </div>

jsFiddle demo

Browser support for CSS Grid.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: