Changing display order with CSS direction property
Few days ago, I stumbled upon an article in my RSS feed that talked about changing the element display order by using different CSS methods. It’s a great article, and you should definitely check it out.
It got me thinking about one of our recent projects here at Slicejack, where we faced a small element display order issue.
In the next few lines of text, I will show you how we ended up solving it by using the CSS “direction” property.
The project we were working on, was a pretty straight forward news website, which had a footer that looked something like the one in the image below.
As you can see, footer contained only three elements:
- Copyright note
- Developer info
- Navigation
It’s was a simple layout, that could have been coded up in just a few minutes. Unfortunately, mobile design complicated things a bit.
Notice the difference in element order?
Desktop view: 1. Copyright note; 2. Developer info; 3. Navigation
Mobile view: 1. Navigation; 2. Copyright note; 3. Developer info
Let me show you how we tackled this ordering problem by using the CSS “direction” property.
First and foremost, our HTML layout:
And some CSS styling:
The HTML markup is pretty straight forward. Not much to explain here.
- <div> elements with “container”, “row”, and “col” classes are grid related
- <nav> element for our navigation
- two paragraphs for our two notices (copyright and developer info), wrapped in a <div>
Element order in the markup matches the mobile view, so if we were to check this HTML and CSS on a desktop, it would look like this:
Notice that the element order doesn’t match the desktop design. To remedy this, we add “direction: rtl” to our “footer” element, which results in the following:
We are getting closer, but we still don’t have the correct element order. To match the design, the two footer notices need to switch places. Also, we need to revert the direction of our navigation items. By adding “direction: ltr” to our “footer__nav” and “footer__content”, we can fix these two issues.
This is our final CSS with ‘direction’ rules added:
The final result is a responsive footer that matches both our mobile and desktop designs. If you don’t believe me, just check out this live DEMO.
The same result can be achieved by using flexbox, so if you don’t have to support older browsers, you can always go that route.
That’s all there is to it! If you are aware of any other CSS ordering methods that could work for our example, please let me know in the comments below.
Cheers!