Did you know about ‘display: contents’ CSS rule?
Responsive Blog Post Display using Grid and display:contents
Consider this blog post display section. On a wider screen, we want the image to be on the right separated from the text. While on a mobile screen, we want the image to appear in between our heading and the paragraph.
This layout could easily be a hero section of your website too. There are multiple ways to approach this, based on the HTML markup. Likely, your markup looks something like this:
With this markup, the desktop layout is straight forward. You can use flexbox like this:
But for smaller screens, how do you get that image in between heading and paragraph?
Introducting display: contents
CSS rule
When you set use display: contents
on an element, that element's children become direct children of the element's parent. It's like, that element disappears from the Markup.
So, in our case, for mobile layout, if we use display: contents
on our .text
element, it gets ignored:
And now it's equivalent to the below markup, for styling:
Now we can use flexbox for the .container
with flex-direction
as column
and then use order
property to get the image element in between heading and para! 🪄
Here's the simplified CSS snippet:
You can see the full working demo on Codepen
Image appears in different places on mobile and in desktop layouts
Hope you liked this issue and learnt something new :) See you next week!