The ultimate CSS battle: Grid vs Flexbox - Flexbox and CSS Grid are two CSS layout modules that have ... The MDN Community has created some thorough docs on the basic differences between Grid and flexbox...đđđ
The ultimate CSS battle: Grid vs Flexbox - Flexbox and CSS Grid are two CSS layout modules that have ... The MDN Community has created some thorough docs on the basic differences between Grid and flexbox...
CSS Flexbox has become extremely popular amongst front-end developers in the last couple of years. This isnât surprising, as it has made it a lot easier for us to create dynamic layouts and align content within containers.
However, thereâs a new kid in town called CSS Grid, and itâs got a lot of the same capabilities as Flexbox. In some cases, itâs better than Flexbox, while in other cases itâs not.
This seems to be a source of confusion for developers. So in this article compare the two modules, both a micro and macro level.
If you want to learn the two modules properly, check out my free courses CSS Grid and CSS Flexbox.
Click on an image to get to its respective course.
Now letâs get started!
If you are to take one lesson from this article, let it be this one:
Flexbox is made for one-dimensional layout and Grid is made for two-dimensional layouts.
This means that if youâre laying out items in one direction (for example three buttons inside a header), then you should use Flexbox:
Itâll give you more flexibility than CSS Grid. Itâll also be easier to maintain and require less code.
However, if youâre going to create an entire layout in two dimensionsâââwith both rows and columnsâââthen you should use CSS Grid:
In this case, CSS Grid will give you more flexibility, make your markup simpler and the code will be easier to maintain.
Now you can, of course, combine the two. In the example above it would be perfect to use Grid for the page layout, and then Flexbox to align the content inside the header. Thisâll give you the best of both worlds. And Iâll show you exactly how to do at the end of this article.
Another core difference between the two is that Flexbox bases in the contentwhile Grid bases in the layout. This might seem abstract, so letâs look at a specific example, as that makes it easier to understand.
Weâll use the header from the previous paragraph. Hereâs the HTML for it:
<header>
<div>Home</div>
<div>Search</div>
<div>Logout</div>
</header>
Before we turned it into a Flexbox layout these divâs would have been stacked on top of each other like this:
Iâve added a little bit of basic styling, which as nothing to do with Flexbox or Grid, so Iâm leaving that out.
However, when we give it a display: flex;
the items will be places nicely on a line.
header {
display: flex;
}
To move the logout button to the far right side, weâll simply target that element and give it a margin:
header > div:nth-child(3) {
margin-left: auto;
}
Which results in the following:
What I want you to notice here is that we leave it up to the items themselves to decide how theyâre placed. We didnât have to pre-define anything else than display: flex;
initially.
This is at the core of the difference between Flexbox and Grid, and it will be more apparent as we recreate this header using Grid.
Even though CSS Grid isnât build to create one-dimensional headers, itâs still a good exercise to do it in this article, as it teaches us about the core differences between Flexbox and Grid.#### Grid header
We can create our header in several different ways using CSS Grid. Iâm going to go with a pretty straight forward one, where our grid has ten columns, each being one fraction unit wide.
header {
display: grid;
grid-template-columns: repeat(10, 1fr);
}
Itâll look identical to the Flexbox solution.
However, we can peek under the hood to see whatâs different. Weâll use the Chrome inspector to inspect the column lines:
The key difference with this approach is that we had to define the columnsâââthe layoutâââfirst. We start with defining the width of the columns, and then we place the content in the available grid cells.
This approach forced us to take a stance on how many columns we wanted to split our header into.
Unless we change the grid, weâre stuck with ten columns. A limitation we wouldnât have had to deal with in Flexbox.
In order to change the logout to the far right hand side, weâll place it in the tenth column, like this:
header > div:nth-child(3) {
grid-column: 10;
}
Hereâs how that looks when weâre inspecting the grid:
We couldnât simply have given it a margin-left: auto;
because the logoutbutton had already been placed in a specific cell in the layout, in the third column. To move it, we had to find another grid cell for it.
Now letâs look at how to use both in combination, merging our header into our website layout. Weâll start by building the website layout.
Hereâs the markup:
<div class="container">
<header>HEADER</header>
<aside>MENU</aside>
<main>CONTENT</main>
<footer>FOOTER</footer>
</div>
Hereâs the CSS:
.container {
display: grid;
grid-template-columns: repeat(12, 1fr);
grid-template-rows: 50px 350px 50px;
}
Weâll place the items on the grid like this:
header {
grid-column: span 12;
}
aside {
grid-column: span 2;
}
main {
grid-column: span 10;
}
footer {
grid-column: span 12;
}
Now weâll simply add the header. Weâll turn the headerâââwhich is an item in our CSS Gridâââinto a Flexbox container.
header {
display: flex;
}
Now we can set the logout button to the right:
header > div:nth-child(3) {
margin-left: auto;
}
And there we have a perfectly fine layout which uses the best from both Grid and Flexbox. Hereâs how the two containers look:
So now you should have a strong understanding of the general and specific differences between Flexbox and Grid, and know how to use them together.
Before we end, I also need to mention browser support. At the time of publishing this article, 92% of global website traffic supports CSS Grid, and itâs climbing.
I believe CSS Grid will turn into a must-have skill for front-end developers. Much like what has happened with CSS Flexbox the last couple of years.
Click the image below to see a preview of the course.
In this article, you will learn how you can use CSS Custom Properties to make your stylesheets a bit more dynamic, perhaps making that extra Sass/LESS step in your asset pipeline obsolete.
If you have been writing CSS for a while, you must have at some point in time felt the need for variables. CSS custom properties are somewhat like CSSâs own implementation of variables. However, when used properly, they can be so much more than just variables.
CSS custom properties allow you to:
var()
 function to use these values in other propertiesAlthough support for CSS custom properties is a bit of a rocky path at the moment, and some browsers support them under flags that need to be activated or set to true beforehand, their support is expected to increase dramatically moving forward, so itâs important to understand how to use and leverage them.
In this article, you will learn how you can use CSS Custom Properties to make your stylesheets a bit more dynamic, perhaps making that extra Sass/LESS step in your asset pipeline obsolete.
The Original, and Less Powerful, CSS VariableBefore we begin to discuss CSS custom properties, it should be noted that for a long time now, CSS has had a sort of variable, and that is the currentColor
 keyword. This rarely used but widely supported variable, refers to the current color value of an element. It can be used on any declaration that accepts a color
 value, and it cascades perfectly.
Letâs take a look at an example:
.element { color: blue; border: 2px solid currentColor; /* Sets a solid, 2px wide, blue border to the element */ }
In addition to cascading, this can also produce the following:
.element span { background: currentColor; /* Sets a blue background color for every span child of .element, unless a color property is declared in this same block */ }.element span.red {
color: red; /* Sets a red background color for every span child of .element that has the class .red, since currentColor is applied to the background of every span child of .element no matter if they have the .red class or not */
}
The main issue with currentColor
, aside from the fact that it wasnât in the specification as a variable per se, is that it only accepts the value of the color property, which can make it difficult to work with in some cases.
One of the main advantages of using CSS pre/postprocessors are is that they allow for values to be stored in a keyword and have them scoped to a certain selector if necessary.
After long being requested by developers, a draft for an interpretation of native variables for CSS was written. These are formally referred to as CSS custom properties, but are also sometimes referred to as CSS variables.
The current specification for native CSS custom properties covers all the same behaviors as pre/postprocessor variables. This enables you to store color codes, sizes with all of the known units, or just integers if needed (e.g., when a you need to use the same divisor or multiplier).
The syntax for CSS custom properties is a bit weird compared to other languages, but it makes a whole lot of sense if you compare their syntax with other features in the same CSS ecosystem:
:root {
--color-black: #2e2e2e;
}.element {
background: var(--color-black);
}
Now, you might be thinking: âWhat sort of syntax is that!?â
Well, Lea Verou explains the reason for this âdash-dashâ syntax with absolute simplicity, as she says in her amazing talk, CSS Variables: var(âsubtitle):
They work exactly the same way as any other CSS property [âŚ]. So many people ask me why we didnât use a dollar [sign] or something like that and the reason we didnât use a dollar [sign] is that we want people to be able to use both SASS, or preprocessor variables and CSS variables. Theyâre both different things, they accomplish different goals, there are things you can do with CSS variables that you absolutely can not with SASS, and there are things you can do with SASS variables you can not do with CSS variables, so we want people to be able to use both of them in the same stylesheet, so you can imagine the dash-dash syntax as like a prefix property with an empty prefix.
We can retrieve the value of the custom property using the var()
 function, which we can use everywhere except for selectors, property names, or media query declarations.
It is worth noting that while pre/postprocessor variables are only used at compilation-time, CSS variables can be used and updated dynamically. What does this mean? It means that they are preserved in the actual CSS stylesheet. So the notion that they are variables will remain even after the stylesheets are compiled.
To make it more clear, let me illustrate the situation using some examples. The following block of code is part of a SASS stylesheet:
:root {
$value: 30px;
}@media screen and (min-width: 768px) {
$value: 60px;
}.corners {
border-radius: $value;
}
This snippet of SASS declarations and rules compiles to CSS as follows:
.corners {
border-radius: 30px;
}
You can see that both the properties inside :root
 and the media
 query get lost after compilation, because SASS variables cannot exist inside a CSS file (or, to be more precise, they can be forced to exist in a CSS file, but are ignored since some of their syntax is invalid CSS), so the variableâs value can not be updated afterwards.
Now letâs consider the same case, but applied using only CSS Variables with no CSS pre/postprocessor applied (i.e., without any no transpilation or compilation being performed):
:root {
--value: 30px;
}@media screen and (min-width: 768px) {
--value: 60px;
}.corners {
border-radius: var(--value);
}
Obviously, nothing changes since we havenât compiled/transpiled anything, and the value of the custom property can be updated dynamically. So, for example, if we change the value of --value
 using something like JavaScript, the value will update in every instance where it is called using the var() function.
The capabilities of custom properties make this feature so powerful that you can even do things like autoprefixing.
Lea Verou sets an example using the clip-path
 property. We begin by setting the value of the property we want to prefix to initial
 but use a custom property, and then proceed to set each prefixed propertyâs value to the custom property value:
* {
--clip-path: initial;
-webkit-clip-path: var(--clip-path);
clip-path: var(--clip-path);
}
After this, all thatâs left is changing the value of the custom property inside a selector:
header {
--clip-path: polygon(0% 0%, 100% 0%, 100% calc(100% - 2.5em), 0% 100%);
}
If youâd like to know a bit more about this, check out Leaâs full article on autoprefixing with CSS variables.
Bulletproofing CSS Custom PropertiesAs was mentioned, browser support for CSS Custom Properties is still largely non-standard. So how can this be overcome?
This is where PostCSS, and its plugin, postcss-css-variables, comes into play.
In case youâre wondering what PostCSS is, check my article PostCSS: SASSâs New Play Date, and come back to this after youâre done. Youâll then have a basic idea of what you can do with this amazing tool and wonât feel disoriented when reading the rest of the article.
With the postcss-css-variables
 plugin, and its preserve
 option set to true, we can keep all the var()
 function declarations in the output and have the computed value as a fallback declaration. It also keeps the computed --var
 declarations. Keep in mind that, using this PostCSS plugin, custom properties can be updated dynamically after the transpilation process, but fallback values will remain the same unless theyâre specifically targeted and explicitly changed individually.
If youâre looking for a pre/postprocessor-free way to use CSS variables, you can always check the current support manually with the CSSÂ @support
 rule and apply a proper fallback when support is patchy or non-existent. For example:
:root {Changing the Value of a Custom Property Using JavaScript
--color-blue: #1e90ff; /* hex value for dodgerblue color */
}.element {
background: var(--color-blue);
}@supports (not(--value: 0)) {
/* CSS variables not supported */
.element {
background: dodgerblue;
}
}
Iâve been mentioning throughout this whole article that variables can be updated using JavaScript, so letâs get into that.
Say you have a light theme and want to switch it to a dark theme, assuming you have some CSS like the following:
:root {
--text-color: black;
--background-color: white;
}body {
color: var(--text-color);
background: var(--background-color);
}
You can update the --text-color
 and --background-color
 custom properties by doing the following:
var bodyStyles = document.body.style;Interesting Use Cases
bodyStyles.setProperty('--text-color', 'white');
bodyStyles.setProperty('--background-color', 'black');
Over the years of development and discussion regarding the specifications of CSS Custom Properties, some interesting use cases have emerged. Here are a few examples:
Theming:Â Using a set of themes for a site is rather easy when implementing CSS variables. Want a light or dark variation of your current style? Just change the value of some custom properties using JavaScript and youâre done.
Spacing tune-ups:Â Need to fine-tune the spacing of a site, say a gutter between columns? Change the value of a single CSS variable and see this change reflected site-wide.
Fully dynamic calc() functions: Now you can have fully dynamic calc()
 functions using custom properties inside these functions, removing the need to make complicated or ephemeral calculations inside JavaScript and then update these values manually on each instance.
CSS custom properties are a powerful and innovative way to bring more life to your stylesheets, introducing completely dynamic values for the first time in CSS.
The spec is currently under Candidate Recommendation status, which means that standardization is right around the corner, a good reason to dive deep into this feature and get the most out of it.
I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.
Thanks For Visiting, Keep Visiting.
â CSS Secrets for Beginners
â Web Design for Beginners: Real World Coding in HTML & CSS
â 5 CSS tips you didnât know you needed
â Build Responsive Real World Websites with HTML5 and CSS3
â Advanced CSS and Sass: Flexbox, Grid, Animations and More!
Originally published on toptal.com
Learn HTML5, CSS3 and Web Development in this awesome course from beginner to expert.
Thanks for watching â¤
If you liked this post, share it with all of your programming buddies!
Follow me on Facebook | Twitter
â Build Responsive Real World Websites with HTML5 and CSS3
â Web Design for Beginners: Real World Coding in HTML & CSS
â How to build and send a HTML Email 2019
â Building a Simple URL Shortener With HTML and Javascript
â 34 Free HTML And CSS Books
â How to build Desktop Apps with HTML, CSS and Javascript?
Wait... CSS algorithms? Can one really write algorithms in CSS?
This talk is all about CSS algorithms: what they are, how to write them, and the potential impacts of a word like "algorithm" when it comes to positioning CSS expertise in the larger context of web development.
Thanks for reading â¤
If you liked this post, share it with all of your programming buddies!
Follow me on Facebook | Twitter
â The ultimate CSS battle: Grid - Flexbox
â How to build a reusable card modal using Vue.js and Tailwind CSS
â How to build Desktop Apps with HTML, CSS and Javascript ?
â HTML5 and CSS3 Fundamentals: Development for Absolute Beginners