The ultimate CSS battle: Grid - Flexbox

The ultimate CSS battle: Grid - 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...👏👏👏

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!

One dimension vs two dimensions

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.

Content-first vs layout-first

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.

Flexbox header

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.

Combining the two

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.

Browser support

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.

How to Make CSS Dynamic with CSS Custom Properties

How to Make CSS Dynamic with CSS Custom Properties

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:

  • Assign arbitrary values to a property with a name of your choice
  • Use the var() function to use these values in other properties

Although 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 Variable

Before 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.

Fully-fledged CSS Variables

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 Properties

As 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 {
--color-blue: #1e90ff; /* hex value for dodgerblue color */
}

.element {
background: var(--color-blue);
}

@supports (not(--value: 0)) {
/* CSS variables not supported */
.element {
background: dodgerblue;
}
}

Changing the Value of a Custom Property Using JavaScript

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;
bodyStyles.setProperty('--text-color', 'white');
bodyStyles.setProperty('--background-color', 'black');
Interesting Use Cases

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.

Breathe New Life into Your CSS Files

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: From Zero to Hero

☞ 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

The Algorithms of CSS: What, How, When

The Algorithms of CSS: What, How, When

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

Learn More

☞ 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