SASS in 15 minutes

If you write a lot of CSS, preprocessor like SASS can significantly ease the amount of your work and your stress levels. Things like SassLessStylus or PostCSS make your CSS files more readable and improve maintainability. Thanks to variables and functions the code will become cleaner, better structured and as a result help developers to work faster and make less errors.

Start

The browser on its own doesn't understand Sass files, so it needs to compile them in the normal plain old CSS. Hence, we'll need something to convert .scss files to .css. And there are several options here:

  • The easiest way - is a browser converter for compilation Sass on the spot — SassMeister.
  • Usage of apps: there are both paid and free ones available. Read more here.
  • If you a command line - lover, you can install Sass on your machine and compile it manually.

If you choose the command line at then end - you can install Sass in its original wrapper, developed on Ruby or you can try Node.js port.

You can compile .scss file using the command line like this:

node-sass input.scss output.css

Also, it is now a good time to mention that Sass offers 2 different types of syntax: Sass and SCSS. Both do the same thing, but developed differently. SCSS is a bit newer and normally considered to be a better option, so we will be using that. If you want to read about the differences on the two - have a read here.

Variables

Variables work in exactly the same way you saw in every other programming language. When declaring, we store a specific value in it, which we usually see in CSS like color, font or any other property like box-shadow.

Below are the examples of such variables in SCSS and CSS.

After compilation, the above will look like this in CSS:

The idea is that it can simplify the process of repetitive usage of variables and also we can quickly change the value of a specific variable where we declare it instead of surfing through your code.

Mixin

Mixin can also be used as a class-constructor in the programming language: you use several properties from the CSS creating a separate object, which later can be used wherever you want assigning different values to its properties.

Have a look at the example below:

Thats what we will see in CSS:

One more way to simplify you work with mixin is to use it with prefixes for browser adaption.

CSS:

Extend

Next nuance that we will look at is @extend. It allows us to inherit CSS properties to one selector from the other one. The principle is somewhat similar to Mixin, but Extend is mostly used to create logical connection between the page elements.

E.g. Extend is used when we need 2 similar elements that has slight differences. For example, let's take 2 buttons: Confirm and Cancel.

CSS:

If you have a look at the CSS code, you will see that Sass combines selectors instead of repeating the same ones several times in the code.

Nested constructions

As you would know, in HTML the developer write code following the 'nesting' principle. In other words, blocks of code are located in other blocks. CSS on the other hand normally looks chaotic in this sense. If that is a problem for you Sass can help you to organise and structure it.


An example of code in SCSS:

And the same in CSS:

Operations

You can do different mathematical operations right inside the code, which massively improve the workflow.

CSS:

Although right now you can do the same thing in CSS by using calc(), the Sass alternative method is faster to write and has mod (%) operation and also can be used in a wider spectre of types.

Functions

Sass provide a huge list of functions. For example, functions for operations on lines, colours or different mathematical operations like random() or round().

To make it a bit more visual let's have a function darken ($color, $amount), which (as you probably guessed) will darken or attach hover effect.

SCSS code:

CSS:

In addition to a huge list of functions, you can also declare your own.

Some parts of the above will eventually get to the normal CSS, but till then preprocessors are a great way to make your life easier and Sass here is a very decent choice.


*Translated from WebDev.

*Join @thefrontend channel for more🔥.

July 8, 2018by The Front End
187
0

Learning Material


☝🏻Setting up the environment with React

(the fastest and easiest way is to use their official 'out of the box' solution)

https://github.com/facebookincubator/create-react-app#create-react-app

☝🏻Thinking in React

(it is pretty specific on how React view development with breakdown into different components. The link also has official facebook tutorial on the right)

https://reactjs.org/docs/thinking-in-react.html

☝🏻Best way to structure your React dev is to split everything in Components/Containers view

https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 

 

React Bootstrap 

(React's bootstrap can slightly vary from a normal one, just to make our development a bit more.. like React style)

https://react-bootstrap.github.io/components.html#page-layout 

Refresh your JS knowledge

https://learnxinyminutes.com/docs/javascript/


☝🏻Firecasts

(the best quick videos I have seen on how firebase work with React. They have a series of videos there on Firebase+React)

To add on the above, this guy explain really well the authentication in React

https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/

More?

a few practical examples in React

https://tutorialzine.com/2014/07/5-practical-examples-for-learning-facebooks-react-framework

A lot of quality content on React with examples

https://reactfaq.site/

July 7, 2018by The Front End
123
0

Cooking with JS asynchronously

What the hell are callbacks, why do I need to promise anything, what's all the fuss about async/await stuff?

If you have ever asked those questions yourself. Here is a quick recipe how to not get confused.

First, let's cook some Carbonara🔥.

To do this, we basically need few things (the example is simplified)

🔸 Cook pasta

🔸 Cook bacon

🔸 Mix the two

🔸 Throw a bit of cheese in

Now that the functions are done, let's call them.

Couldn't be easier, right? What we end up to see in the console is a nice list of our actions.

Ready to get your lunch? Not so fast. To the left from the log you can see the time at which the function was fired. Looks like we outperformed Michelin star chefs and got pasta and bacon ready in just a few milliseconds.

Doesn't look too realistic..

Let's bring us back to reality and simulate at least a tiny lag in the first 2 functions. Don't worry too much about the setTimeout function for now, what it does is simply waits for a bit and then logs the stuff we want.

Shouldn't make it catastrophic, let's see how the console looks right now.

Shit. Something clearly got out of control. One cannot add bacon to pasta, put cheese on top before those 2 are not ready.

This is what real life looks like though. And the problem we experienced here has something to do with the fact that all functions were fired simultaneously. In other words, JS didn't care whether we finished cooking pasta, it went on launching other functions in the meantime.

Since the example was simplified, you can only imagine what kind of damage to your app would this bring in the real world.

Callbacks

One way to deal with that is to use something known as callbacks. Regardless your favourite computer language, this will refer to a "call after" function, or in other words, anything executable that can be passed as an argument in your code.

Sounds, realistic. Let's give it a shot. To show how the callbacks work, the most simplified example will look like below:

Also we are creating another function to notify us when the cooking has been finished.

Then calling all function and the first 2 with callbacks.

Looks like it worked. But bear in mind that the purpose here is to just show you the concept of callbacks. And you can guess that the more functions you have the more complicated it will get. Eventually with this technique, you might end up having loads of functions calling each other here and there. This has a huge potential to make your code massive and unreadable.

That's where the promises come in.

Promises

To put it simply, promises help us to wrap our functions and wait till something returns before moving on to the next function.

In our case, we would like to cook the pasta first, then do the bacon and then all the mixing/finishing stuff.

This is how the implementation can look like. We creating a promise, which will simply return the check emoji on success (on so-called 'resolve') and this will happen after a short time lag.

We then take this result and push it to our prepare() function. The prepare function has also been slightly modified and now also returns the dish after writing it to the console. This should then push it to the next prepare() and so on.

Looks good, we are now waiting for pasta to be prepared, then do the bacon when the pasta is ready, then the rest. This called chaining as we chain through all the .then.

The above helps us to ensure we wait till the promise is resolved and then start cooking pasta. One example of how functions can be fired asynchronously.

In the real world, you normally return something from the function then send it to the next function to use. For example, you could fetch some data from an API, parse it and then send to the next function (which would fail to properly run without getting something from the API first).

The above example again, was simplified to familiarise you with the concept, in real life you will also specify what happens if the promise was rejected and catch errors in each .then

While this is still a better, cleaner solution than callbacks - it can also get pretty messy.

Sync/Await

Another way, which is still fairly new and was introduced with ES8 is sync and await. And the main goal is.. well make your code cleaner and smaller again.

The idea here is extremely simple. We have to create a new async function, which is a fancy way of making the functions inside work asynchronously and specify whatever part of it needs to calm down and wait for a bit. This can nicely work with promises, but you can also just wait till the function returns you something.

So for now let's actually drop in a delay for each of the actions to simulate real case. For this we can create a simple function:

Similar to the Promise example, we are creating a delay and on success it should pass the element further in the chain. Also, as it would happen in normal world, we substituted all our console.log() with return , so that now all functions should return something.

Finally, instead of calling all functions one by one, we are going to create a separate function for this and call it later. And all you have to remember is this 2 things:

🔸 You need to use the word async next to the function - this will allow usage of await and will make your code to work asynchronously

🔸 You will have to specify await where something needs to wait till it gets the something back

And please - Do not try to use awaits without specifying async first and do not attempt to await for something in the top level - this wouldn't work. The 2 aforementioned points are must-have.

By looking at the code above, we should expect to see the following process:

'start cooking' will be printed in console → then the variable will wait for 1250ms simulating the time delay for the specified functions. After each function we are also printing out whatever it got after waiting.

Remember, we are now returning things, not printing them in the console. So our combine variable for example will have to use dish and dish2 to mix them and won't be able to do it until both are done.

Finally, we are also adding a nice checkbox ✅ after the element showing us that it has been retrieved from the waitTillFinish() function.

Here, let's have a look what we got.

As you can see now we doing it all with approx. a 1 second delay (still to quick, but good for demonstration). For combination we obviously getting 2 checks meaning pasta and bacon are ready and then the mixing is also done.

You can try it yourself in the Chrome Dev tools, some things will differ, like you won't have to use .this word and probably will need to specify function Name when creating one.

Now that is done go make yourself some Carbonara and make sure you don't add cheese until pasta and bacon are done (wouldn't be good).

Join our telegram @thefrontend

May 18, 2018by The Front End
750
1

Collation of beautifull effects in CSS/SVG/JS

Here is a list of some the nice effects, interesting ideas and useful components.

Don't reinvent the wheel, have a look and maybe on of the projects can fit in nicely into your development.

Animation about designers

Tech: CSS

Author: @miocene

View code


A horse in motion

Tech: CSS + Variative font

Author: @lorp

View code


Hanoi Tower (try to solve)

Goal - move all discs from the left tower to the right one.

Tech: CSS

Author: @finnhvman

View code


Choose any time of the day

Tech: CSS, SVG, JS

Author: @olivaele

View code


SVG switcher between tabs

Tech: CSS, SVG, JS

Author: @ainalem

View code


Stretch scroll effect

Tech: CSS, JS

Author: @nathantaylor

View code


Interactive SVG mask

Tech: SVG mask, JS

Author: @PointC

View code


Day and Night

Tech: CSS-variables, JS

Author: @CameronFitzwilliam

View code

Hope you liked it.

🔥Join our telegram @thefrontend

*Translated from css-live

May 15, 2018by The Front End
52
0

TOP 10 CSS interview questions

Below is a list of CSS interview questions that you are very likely to face when applying for a front end position.

🤨Q. What are the three main ways to add CSS to a webpage? Describe the advantages and disadvantages of each method.

🤓A. There are three ways to apply CSS to a webpage—inline, embedded, and as an external style sheet. The three approaches along with their pros and cons are described below.

  • Inline CSS can be written directly into the HTML elements as a style attribute. The primary advantage of inline CSS is the ability to override other style specifications in the single instance of an HTML element that it is applied to. However, this is only feasible if there are a small number of style definitions. It is generally better to use embedded or external style sheets for more complex styles.
  • External style sheets allow the developer to separate style from content, and control multiple HTML documents from a single separate file, making it easy to style the entirety of a site with a single document. It enables complex styling through classes, selectors, and other grouping methods. The disadvantage of an external CSS file is that it must be downloaded first for the HTML file to be properly rendered.
  • Embedded CSS can be written within the <style> tags inside the <head> section of an HTML document. It shares many of the same advantages as the External Style Sheet, with access to classes, selectors, and more complex styling. Embedded CSS has the added advantage of loading with the HTML document—no extra download required. However, that also means that any external HTML documents will not inherit the styling of CSS written within these tags.

🤨Q. What are CSS media queries and what are they used for?

🤓A. CSS media queries are the filters that make responsive web design (RWD) possible. With the introduction of laptops, tablets, and smartphones with screens of varying sizes and aspect ratios, RWD is crucial for modern day app development. CSS media queries adjust content style based on device characteristics like width, height, orientation, resolution, and display type. When used properly, the end result is a website or app capable of providing a sleek UI/UX across multiple devices.

🤨Q. What is a CSS preprocessor? Would you recommend using one for this project?

🤓A. A preprocessor is an abstraction layer built on top of CSS. Preprocessors extend the functionality of CSS by offering powerful features like variables, inheritable “classes” called extends, and “function-like” mixins. Sass, LESS, and Stylus are some of the more well-known preprocessors—try asking the developer which one they prefer more. Selecting a preprocessor really boils down to preference, and it can be revealing to see how a particular developer might decide to use one over the other for your project.

🤨Q. List the basic layout components of the CSS box model with a brief description for each

🤓A. In many ways, front-end web design is all about managing rectangles, and the CSS box model provides a layout paradigm for HTML elements that you can use to structure a webpage. The basic components are described below.

  • border: The border surrounding the padding.
  • content: Any text or images within the box.
  • margin: The transparent area surrounding borders.
  • padding: The transparent area surrounding content.

🤨Q. How would you implement the basic layout components of the box model in CSS? Give an example.

🤓A. Each element of the box model—border, content, margin, and padding—can be specified independently for each side of the element by listing dimensions in the following order: top, bottom, right, and left. Alternatively, multiple sides can be specified as a group by listing fewer parameters. An example has been provided below.

margin: 50px 100px 100px 50px;
/* Sets the top, right, bottom and left margins */

margin: 25px;
/* Sets the margin on all sides */

padding: 50px 100px;
/* Sets the top/bottom margin as a group and the right/left margin as a group */

🤨Q. Give an example of how you would use counter-increment and counter-reset in CSS to create automatic numbering within a webpage.

🤓A. The counter-reset and counter-increment properties allow a developer to automatically number CSS elements like an ordered list (<ol>). The counter-reset property resets a CSS counter to a given value. The counter-increment property then increases one or more counter values. Automatic numbering within a webpage is often useful, much like the section headers within this article. An example of how to use counters in CSS is displayed below.

body {
    counter-reset: foo;
}

h1 {
    counter-reset: bar;
}

h1:before {
    counter-increment: foo;
    content: "Section " counter(foo) ". ";
}

h2:before {
    counter-increment: bar;
    content: counter(foo) "." counter(bar) " "; 
}

🤨Q. Describe the following common CSS units of length: cm, em, in, mm, pc, pt, and px.

🤓A. There are many ways to express units of length within CSS, but these are just some of the more common ones.

  • cm: centimeters
  • em: a relative unit of measurement based on the size of a font
  • in: inches
  • mm: millimeters
  • pc: pica, a unit of length equivalent to 12 points, or 1/6 of an inch
  • pt: 1/72 of an inch
  • px: a device-specific relative measurement equivalent to a certain number of pixels on a display

🤨Q.What are CSS vendor prefixes? Can you name some of the more common ones that you’re familiar with?

🤓A. Depending on your project, you might be looking for a CSS developer who can take advantage of experimental non-standard features that are only available on certain platforms. Vendor prefixes are extensions to CSS standards that can be added to these features to prevent incompatibilities from arising when the standard is extended. CSS vendor prefixes for some common platforms are listed below.

  • -webkit-: Android, Chrome, iOS, and Safari
  • -moz-: Mozilla Firefox
  • -ms-: Internet Explorer
  • -o-: Opera

🤨Q. How do you define a pseudo class in CSS? What are they used for?

🤓A. You can define a pseudo class by listing the selector followed by a colon and finally the pseudo class element. Pseudo classes can be used to give elements special states—the most common example being a:hover, which is used to change the color of a link when a mouse hovers over it. Other uses include using distinct styling for visited and unvisited links and styling an element differently when focused.

🤨Q. How would you select all the PDF links in the code block below with a single line of code?

<body>

<p><a href="default.asp" target="_blank">This is a link</a></p>
<p><a href="mydocument.pdf" target="_blank">This is a PDF</a></p>
<p><a href="default.asp" target="_blank">This is a link</a></p>
<p><a href="mydocument.pdf" target="_blank">This is a PDF</a></p>

</body>

🤓A big part of CSS is selecting and stylizing particular elements on a page. This question tests a developer’s knowledge of attribute selectors. All the elements of interest on the page happen to be links, but not all links are linking to PDFs. In CSS you can target the ending of the PDF link “.pdf” to quickly select all the PDF files by using the [attribute$=”value”] selector, which selects elements whose value ends with a specified value. In this case, we can use a[href$=“.pdf”] to select all PDF links.

May 6, 2018by The Front End
22
0
Show more