How to get divs to stack on mobile and inline on desktop screens?

Viewed 150

I'm struggling to use Tailwind CSS to display inline on large sizes and block on small sizes.

Below is my code:

<div class="block md:flex md:justify-between md:text-left text-center">

    <div class="order-2 md:order-1">Div 1</div>
    <div class="order-1 md:order-2">Div 2</div>

</div>

On a large screen it should look like:

Div 1                                                                     Div 2

and on a small screen:

                                       Div 2
                                       Div 1
2 Answers

Media Queries

You can use media queries to change styling depending on certain conditions:

<div class="container">
  <div>ONE</div>
  <div>TWO</div>
</div>
.container {
  /* Mobile by default as Roy pointed out */
  display: flex;
  flex-direction: column;
}

@media (min-width: 768px) {
  /* For desktops */
  .container {
    flex-direction: row;
  }
}

Here is a JSFiddle for you to play with.

If you really want to check whether it is a mobile device, there is probably a library for that in the framework you are working with.

Or you can check for it yourself with some JavaScript as explained here with some examples.

But the device type should not actually affect the decision of how to display items. You should just take into account screen size and ratio, and thus use the media-query.

Related