CSS: From Zero to Hero

CSS: From Zero to Hero

CSS defines the way things look on your websites. HTML is your content, JavaScript adds interaction, but the appearance comes down to CSS. CSS is super powerful, and has a ton of awesome stuff built in. This post will take you from introductory syntax through creating layouts and making sites responsive!

CSS defines the way things look on your websites. HTML is your content, JavaScript adds interaction, but the appearance comes down to CSS. CSS is super powerful, and has a ton of awesome stuff built in. This post will take you from introductory syntax through creating layouts and making sites responsive!

Syntax

CSS is comprised of selectors and declarations. Selectors are how we tell CSS which elements to apply styles to. Declarations are the actual styles that will be applied for that element, i.e. they are everything within the braces. Within those declarations, we have properties and values. The properties are the type of style we are applying, the value is what we are actually applying.

The above CSS is saying, make the font color for all h1’s blue. The h1 is the selector, the declaration is everything between the braces, the property is color, and the value is blue.

One final piece of CSS syntax is comments - these are ignored by the browser – they are just there for humans to document their code. In CSS these look like the following:

/* this is a comment */


Selectors

In CSS, we will use selectors to specify which HTML elements we want to style. Sometimes, this will be every element on the page. Other times, we will only want to select certain elements.

Sometimes, we will want to select each instance of an element on the page, for example, all h2's. We can select elements with their names!

h2 {
  color: blue;
  font-family: sans-serif;
}


Sometimes, we will instead want to select groups of elements – say we only want certain paragraphs to be bolded, we can use classes to differentiate between those paragraphs.

<h2 class="center">Hello World</h2>
<h2 class="center">Hello World</h2>
<h2>Hello World</h2>


We differentiate element and class selectors by putting a . before the class name in CSS – that way CSS knows we are looking for a class named center instead of an element!

.center {
  text-align: center;
}


Now, the first two h2 tags with the center class on them will be centered, and the third, without that class, will still look normal.

There are also some more complex selectors, such as:

h1, h2, h3 {
  /* The commas allow you to group selectors! In this case, all h1-h3's will be blue */
  color: blue;
}

h3:hover {
  /* pseudo-classes allow us to select elements in certain states. So, in this case, when an h3 is hovered, it will be pink! */
  color: pink;
}


Here’s more about pseudo-classes, and here’s an awesome game to practice with more complex selectors.

You may have used IDs for JavaScript code or other web development; however, I don’t recommend using them for CSS, since they are only on one element and you want your code to be reusable!

Properties

Let’s talk about the basic properties in CSS and how you can use them! We’ll go into layout, which tends to be a little trickier, further down in this post, but for now, we’ll go over color and text styling!

Color

There are a couple ways you can add color to a document using CSS, including text and backgrounds. Also, there are a couple of ways to represent colors in CSS.

The first is using named colors. There are 140 colors with names in CSS, these allow you to just put in a name and use them!

.red {
  background-color: tomato;
}


But — there are a lot more than 140 colors out there, so we also have a few more complex ways to represent more colors as well. These are based on the amount of red, green, and blue that comprise a color. Imagine you had three lights, one of each of these colors, and a background. If all three lights were off, then the background would be black. If all three were turned all the way up, the background would be white. And, if one of the lights was turned all the way up but not the others, the background would be that color. Then, the lights can be turned up in combination to create any color.

The RGB, RGBA, and hexadecimal colors are all derived from the above color combinations. Each color of the red, green, and blue “lights” can be given a value from 0 to 255, so that each value can be stored in one byte. In RGB and RGBA, you use base 10 numbers to represent the values, and in hex values, you use the hexadecimal system. RGBA values also have “alpha” values, which are the opacity of the color.

You can color text, backgrounds, borders and more with the above system!

Text

Another really important CSS feature is styling text. You can choose fonts, text spacing, and sizing.

There are some fonts that are built into most computers, which are referred to as web safe fonts. You can also add fancy fonts by including a font file. You can use sites like Google Fonts to find ones that you like for your sites.

body {
  /* if the user's computer has Arial, use that, if not Helvetica, 
  then fall back to the operating system's default sans-serif font */
    font-family: Arial, Helvetica, sans-serif;
}


You can also change the size of text in a couple different ways — the first is pixels — which is usually the most beginner-friendly, then there’s also ems and rems, which allow you to scale fonts differently. You can read more about those here.

The Box Model

CSS operates with the box model. First, you have your content. If you want to add spacing around that content within the background or border around it, you use padding. Then, you can add a border, which will normally be colored differently and patterned. Finally, outside of the background and border is the margin — this will be spacing between our element and other elements on the page.

One quick helpful margin snippet is margin: 0 auto;, which allows you to center most elements horizontally. The 0 value means that there is no margin on the top and bottom of the element. Auto adds equal margin to both sides of the element, centering it in its container.

Display

One of the more important CSS attributes is display. There are a few values you can use here. The first is none which hides the content. This can be helpful for hiding some content on different size screens or due to JavaScript events. inline removes linebreaks after elements, and it also means that adding height and width won’t have an effect. blockmeans that the next element will be on the next line. inline-block is similar to inline, though you can apply height and width to the element. Fixed and sticky displays make elements stay in positions These are generally the most used and most traditional display properties, however, two more recent ones have really changed the layout game.

Layouts

Usually one of the trickier parts of CSS is creating layouts for your webpages. Getting things aligned properly used to be much more difficult than it is now, due to CSS Grid and Flexbox, two newer CSS display attributes . If you would like to learn them in more depth, CSS Tricks has great guides for both Grid and Flexbox. I’ll go over a few tricks here too!

In order to center an element horizontally, you can normally use either text-align: center; or margin: 0 auto;. But — vertical centering used to be more difficult. Good news! Flexbox made it a lot easier. The following snippet placed on the parent of the element you’re trying to center will center it both horizontally and vertically.

parent {
  display: flex;
  align-items: center;
  justify-content: center;
}


You can create rows of elements with CSS grid really nicely.

.cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}


The above code generates three columns of equal size on the page. The grid gap adds spacing between each column.

In addition, they make the “holy grail” three column plus header and footer layout a lot easier — check out this post for a couple ways on how to acheieve it with CSS Grid!

Defaults

Sometimes, there may be styling on your page that seems to be coming from nowhere. The browser actually has some styles pre-written for you. For example, there’s an 8px margin on the body, a 2px border on table blocks, and headers have larger fonts. Sometimes you don’t want these pre-loaded styles, so you can override them!

Cascade

One of the more notorious and occasionally controversial CSS features is the cascade. This mimics inheritance in object-oriented programming, and it defines how styles override one another. If developers use a CSS library, such as Bootstrap, this may be more difficult to navigate.

CSS selectors have various levels of specificity which define how styles are overridden when more styles are applied.

If, for example, we have the following CSS code:

body {
  font-family: sans-serif;
}


All of the text with in our body tags will be sans-serif — even if they are also within a h1 or p or any other tag. But, sometimes we’ll want h1’s to be serif instead, which we can add like so:

h1 {
  font-family: serif;
}


Now our h1’s have a serif font, all other tags within the body are still sans-serif.

Also, different selectors have different levels of specificity. ID’s are the most specific, though I generally don’t use them for CSS since using them isn’t very modular, then classes, then elements themselves, then their parent elements. So, if I add styling to a class, it will override styles added to the element. Using the cascade can be tricky, but it makes your CSS more reusable.

Media Queries

Sometimes you will want certain attributes to change depending on screen size. You can do this using media queries.

The following CSS selectors will only apply when the screen is smaller than 800px across. You can change to min-width for mobile first!

@media only screen and (max-width: 800px) {
  body {
     background-color: MediumOrchid;
  }
}


Animations

CSS allows users to create animations with keyframes. You can specify attributes at certain points in the animation, how long that animation will take, and the timing function performed.

In addition, you can add transforms that are applied when a pseudo-selector is added, such as an element is hovered over. These are super performant!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

7 Best Vue CSS Component for Your App

7 Best Vue CSS Component for Your App

Vue CSS frameworks are great for many reasons; code is more universally understood, web applications are easier to maintain, and prototyping becomes less of an extra step.

Vue CSS frameworks are great for many reasons; code is more universally understood, web applications are easier to maintain, and prototyping becomes less of an extra step and more part of the development process.

1. Tailwindcss-Vue

Tailwindcss-Vue is a library of UI components for Vue.js built using the Tailwind CSS utility-first CSS framework.

Download: https://github.com/advanced-data-machines/tailwindcss-vue/archive/master.zip

2. @zeit-ui/vue

Vue implementation for Zeit Style, originating from Zeit Design.

@zeit-ui/vue is a Vue implementation for zeit style, originating from Zeit Design. Lean more at GITHUB.

The design of the Zeit is concise and aesthetic feeling, this is an important reason for popular of Zeit. Now you can use them through the @zeit-ui/vue.

Download: https://github.com/zeit-ui/vue/archive/master.zip

3. CSSeffectsSnippets

Click on the animation to copy it to your clipboard

Demo: https://emilkowalski.github.io/css-effects-snippets/

Download: https://github.com/emilkowalski/css-effects-snippets/archive/master.zip

4. Vue Cirrus

A fully responsive and comprehensive CSS framework with beautiful controls and simplistic structure. Cirrus is designed to be adaptable to existing themes or when starting fresh. These are the Vue Components for this CSS framework.

Demo: https://florianwoelki.github.io/vue-cirrus/#/

Download: https://github.com/FlorianWoelki/vue-cirrus/archive/master.zip

5. Vue CSS Modules

Seamless mapping of class names to CSS modules inside of Vue components.

Download: https://github.com/fjc0k/vue-css-modules/archive/master.zip

6. BG MixMaster 90 — CSS Background Grid /Pattern Generator

make a background grid (like graph paper) using only one background gradient property and ended up with this killer mix tape for making all kinds of background grids and patterns.

Download: https://codepen.io/jasesmith/pen/YZEYRL

7. CSSOBJ

CSS Rules from JS, change rules dynamically, CSSOM, css modules, auto vendor prefixer, media query for old browsers.

CSS in JS solution, create CSSOM and CSS rules from js, features:

  • CSS Rules create and diff
  • CSS modules with local class
  • Auto vendor prefixer
  • Media query for old browsers
  • Dynamically change CSS

Demo: https://cssobj.github.io/cssobj-demo/

Download: https://github.com/cssobj/cssobj/archive/master.zip

Using CSS Quickies - CSS variables

Using CSS Quickies - CSS variables

Quickies CSS Tutorial: CSS Variables - How to create white - dark themes easily

What is CSS Quickes?

I started to ask my beloved community on Instagram: "what CSS properties are confusing for you?"

In "CSS Quickies" I will explain one CSS property in deep. These are community requested properties.

I'm also live streaming while coding on twitch.tv if you want to spend some fun time or you can ask me any question!

Let's talk about Custom properties aka CSS Variables.

Finally! If you ever have worked with CSS and wanted to keep your design consistent? Or was it more like at some pages, your website had different padding, margin or colors?

Maybe you wanted to implement a dark theme? It was possible, but now it has become easier!

Of course, if you have used LESS or SASS, then you know variables, and now they are finally supported natively. 😁

Let's have a look at it!

Defining a CSS variable

You define a CSS variable with prefixing a CSS property with --. Let's look at some examples.

:root{
  --example-color: #ccc;
  --example-align: left;
  --example-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
}

Your first question is: "What is that ':root' pseudo-class?".

Good question! The :root pseudo-class is as you would use the html selector except that the specificity is higher of the ':root' pseudo-class. This means that if you set properties in the :root pseudo-class it will win over the html selector.

Okay, the rest is pretty simple. The custom property --example-color has the value of #ccc. When we use the custom property, for example, on the background-color property, the background of that element will be a light gray. Cool right?

You can give the custom property, aka CSS variable every value you could give any other property in CSS. It is okay to use left for example or 10px and so on.

Using CSS variables

Now that we know how to set CSS variables, we need to learn how to use them!

For this, we need to learn the var() function.

The var() can have two arguments. The first argument needs to be a custom property. If the custom property is not valid, you want to have a fallback value. To achieve this, you simply need to set the second argument of the var() function. Let's look at an example.

:root{
  --example-color: #ccc;
}

.someElement {
background-color: var(--example-color, #d1d1d1);
}

This should be now pretty straightforward for you to understand. We are setting the --example-color to #ccc and then we are using it in .someElement to set the background color. If something goes wrong and our --example-color is not valid, we have a fallback value of #d1d1d1.

What happens if you don't set a fallback value and your custom variable is invalid? The browser then will act as if this property was not specified and do its regular job.

Tips and tricks
Multiple fallback values

What if you want to have multiple fallback values? So you would think you could do the following:

.someElement {
background-color: var(--first-color, --second-color, white);
}

This will not work. After the first comma var() treats everything even the commas as a value. The browser would change this into background-color: --second-color, white;. This is not what we want.

To have multiple values, we can simply call var() inside a var(). Here comes an example:

.someElement {
background-color: var(--first-color, var(--second-color, white));
}

Now this would produce our desired outcom. When both --first-color and --second-color are invalid then the browser will set the background to white.

What if my fallback value needs a comma?

What to do if for example, you want to set a font-family in in the fallback value and you need to specify more then one font? Looking back at the tip before this should be now straight forward. We simply write it with the commas. Example time:

.someElement {
font-family: var(--main-font, "lucida grande" , tahoma, Arial);
}

Here we can see the after the first comma the var() function treats everything like one value.

Setting and getting custom properties in Javascript

In more complex apps and websites, you will javascript for state management and rendering. You also can get and set custom properties with javascript. Here is how you can do it:

    const element = document.querySelector('.someElement');
// Get the custom propety
element.style.getPropertyValue("--first-color");
// Set a custom propety
element.style.setProperty("--my-color", "#ccc");

We can get and set the custom properties like any other property. Isn't that cool?

Making a theme switcher with custom variables

Let's first have a look at what we will do here:


The HTML markup
<div class="grid theme-container">
<div class="content">
<div class="demo">
<label class="switch">
<input type="checkbox" class="theme-switcher">
<span class="slider round"></span>
</label>
</div>
</div>
</div>

Really nothing special here.

We will use CSS grid to center the content that's why we have a .grid class on our first element the .content and .demo Classes are just for styling. The two crucial classes here are .theme-container and .theme.switcher.

The Javascript code
const checkbox = document.querySelector(".theme-switcher");

checkbox.addEventListener("change", function() {
const themeContainer = document.querySelector(".theme-container");
if (themeContainer && this.checked) {
themeContainer.classList.add("light");
} else {
themeContainer.classList.remove("light");
}
});

First we are selecting our .theme-switcher input and the .theme-container element.

Then we are adding an event listener that listens if a change happens. This means that every time you click on the input, the callback for that event listener will run.

In the if clause we are checking if there is a .themeContainer and if the checkbox input is checked.

When this check is true, we are adding the .light class to the .themeContainer and if it is false, we are removing it.

Why are we removing and adding the .light Class? We will answer this now.

The CSS code

Since this code is lengthy, I will show it to you step by step!

.grid {
display: grid;
justify-items: center;
align-content: center;
height: 100vh;
width: 100vw;
}

Lets first center our content. We are doing this with css grid. We will cover the grid feature in another CSS quickies!

:root {
/* light /
--c-light-background: linear-gradient(-225deg, #E3FDF5 0%, #FFE6FA 100%);
--c-light-checkbox: #fce100;
/
dark */
--c-dark-background:linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(0,0,0,0.15) 100%), radial-gradient(at top center, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.40) 120%) #989898;
--c-dark-checkbox: #757575;
}

Puh this is a lot of code and numbers but actually we are not doing much here. We are preparing our custom properties to be used for our theme. --c-dark- and --c-light- is what I have chosen to prefix my custom properties. We have defined a light and a dark theme here. For our example we just need the checkbox color and the background property which is a gradient in our demo.

.theme-container {
--c-background: var(--c-dark-background);
--c-checkbox: var(--c-dark-checkbox);
background: var(--c-background);
background-blend-mode: multiply,multiply;
transition: 0.4s;
}
.theme-container.light {
--c-background: var(--c-light-background);
--c-checkbox: var(--c-light-checkbox);
background: var(--c-background);
}

Here comes an integral part of the code. We now see why we named the .theme-container How we did. It is our entrance to have now global custom variables. We don't want to use the specific custom variables. What we want is to use global custom variables. This is why we are setting --c-background. From now on, we will only use our global custom variables. Then we are setting the background.

.demo {
font-size: 32px;
}

/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}

/* Hide default HTML checkbox /
.switch .theme-switcher {
opacity: 0;
width: 0;
height: 0;
}

This is just some boilerplate code to set our style. In the .demo selector, we are setting the font-size. This is the size of our symbols for the toggle. In the .switch selector the height and width is how long and wide the element behind our toggle symbol is.

/ The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--c-checkbox);
transition: 0.4s;
}

.slider:before {
position: absolute;
content: "🌑";
height: 0px;
width: 0px;
left: -10px;
top: 16px;
line-height: 0px;
transition: 0.4s;
}

.theme-switcher:checked + .slider:before {
left: 4px;
content: "🌞";
transform: translateX(26px);
}

Here we can finally see our custom properties in action besides using them directly in the .theme.container and again a lot of boilerplate code. As you can see, the toggle symbols are simple Unicode symbols. This is why the toggle will look different on every OS and mobile phone vendor. You have to keep this in mind. Important to know here is that in the .slider:before Selector, we are moving our symbol around with the left and top properties. We are doing that also in the .theme-switcher:checked + .slider:before but only with the left property.

/* Rounded sliders */
.slider.round {
border-radius: 34px;
}

This again is just for styling. To make our switch rounded on the corners.

That is it! We now have a theme switcher which is extendable. ✌😀

Originally published by lampewebdev at  dev.to

====================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

The ultimate CSS battle: Grid - Flexbox

Build a Custom Full Page Slider with CSS and JavaScript

The main differences between Flexbox and CSS Grid