What would be the best way to handle an element which needs to stay in a specific place if the screen width is > X and stay in another place if screen width < X?
Example: https://jsfiddle.net/ovujgsz0/7/
I want the left column to sit under the right column if the screen size is smaller than 1024px.
One way that I see is to declare the div#leftColumn
in both places (initial place and next to div#rightColumn
) and then just use tailwind classes to display it depending on the screen size. But it doesn’t seem right.
What if I have a bigger and more complex component? I feel like this solution would pose problems with rendering more content than necessary.
3
Answers
You’re right that there is a better way 🙂
To solve this problem, you can use the
@media screen
query. Using@media screen
, you can specify a maximum width, under which a specified block of CSS will be applied. In your case, what you should change is thedisplay
attribute of the parent/container div.display: flex
,flex-direction: row
will make your elements render side-by-side in a row.display:grid
, and render the three child divs in a grid as you specified (leftColumn
belowrightColumn
).Here’s an example using the code from your fiddle:
In this solution, the grid layout only applies when the screen is narrower than 1024px.
You can use a https://cssgrid-generator.netlify.app/ to try different grids
You can achieve this with a grid layout and by wrapping the sidebars inside a container that has the
display: contents;
property.Here’s an example using Tailwind.
Using CSS layout tricks as an alternative to duplicate rendering of elements is usually a good idea. But moving an element left or right is not simple, especially if you want those elements to remain aligned with each other after the shift.
Eventually I found a way to make the
left column
still align with theright column
after moving it to the right, but the downside is that it’s out of the document flow and requires pre-calculating the width of theleft column
element. However, because of the grid layout, it’s not difficult to pre-calculate element widths. It’s not very elegant overall, but it works:DEMO on tailwind play
It’s worth noting that tricks are just tricks. CSS can’t achieve everything in layout. If a more complex layout change arises that CSS can`t easily implement, rendering it twice may be a simpler and more flexible approach.