A common question I see being asked is, “How do I display widgets placed in a widget area in columns?”
In this tutorial, I provide basic Flexbox CSS code for arranging three child elements of a container side by side in columns.
Screencast:
Given the HTML structure of
we begin by declaring display
property of the container as flex
.
.home-bottom {
display: flex;
}
Then to display the children far apart i.e., left most appearing at left, right most appearing at right and the middle one in the center we add justify-content: space-between
for the parent/container.
.home-bottom {
display: flex;
justify-content: space-between;
}
If the three widgets or child elements were not having equal widths, you could set the width of each to something like 32% (less than 33.333% or else they will be stuck to each other).
Next, at the media query for a width below which the children should appear stacked, we set flex-direction: column
for the container so the flex axis is vertical (default is horizontal). Flex items flow along the flex axis.
@media only screen and (max-width: 340px) {
.home-bottom {
flex-direction: column;
}
}
Putting this together, we have
.home-bottom {
display: flex;
justify-content: space-between;
}
@media only screen and (max-width: 340px) {
.home-bottom {
flex-direction: column;
}
}
Finally, we need to add browser vendor prefixes to the Flexbox CSS. I use this handy codepen for that. Simply replace the CSS in the codepen with yours, click on the down arrow at the right and click “View Compiled CSS”.
In this example, that would be
.home-bottom {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
}
@media only screen and (max-width: 340px) {
.home-bottom {
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
}
If you set the width of a flex-item to a %, it will keep shrinking–even with`. flex-direction: column`, you’d see that widget at 32% of your phone screen. Instead, you want to use the `flex` property (required by some browsers to render flex items properly anyway), like this:
`.home-bottom .widget {
flex: 0 1 320px;
}`
For that, I reset the widths of the children back to 100% in the media query.
Hi Sridhar,
Can you tell me what browser extension you used to search for the css flex property justify-content: space-between; ?
That looks handy!
Thanks 🙂
Hi Caroline,
It’s not a browser extension. It is SnippetLab’s menu icon. I use it to store all my code snippets.
https://www.renfei.org/snippets-lab/
Aaah! Very cool, thanks 🙂